]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/controlflow.rs
rollup merge of #19842: frewsxcv/rm-reexports
[rust.git] / src / librustc_trans / trans / controlflow.rs
1 // Copyright 2012 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
11 use llvm::ValueRef;
12 use middle::def;
13 use middle::lang_items::{PanicFnLangItem, PanicBoundsCheckFnLangItem};
14 use trans::_match;
15 use trans::adt;
16 use trans::base::*;
17 use trans::build::*;
18 use trans::callee;
19 use trans::cleanup::CleanupMethods;
20 use trans::cleanup;
21 use trans::common::*;
22 use trans::consts;
23 use trans::datum;
24 use trans::debuginfo;
25 use trans::expr;
26 use trans::meth;
27 use trans::type_::Type;
28 use trans;
29 use middle::ty;
30 use middle::ty::MethodCall;
31 use session::config::FullDebugInfo;
32 use util::ppaux::Repr;
33 use util::ppaux;
34
35 use syntax::ast;
36 use syntax::ast::Ident;
37 use syntax::ast_util;
38 use syntax::codemap::Span;
39 use syntax::parse::token::InternedString;
40 use syntax::parse::token;
41 use syntax::visit::Visitor;
42
43 pub fn trans_stmt<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
44                               s: &ast::Stmt)
45                               -> Block<'blk, 'tcx> {
46     let _icx = push_ctxt("trans_stmt");
47     let fcx = cx.fcx;
48     debug!("trans_stmt({})", s.repr(cx.tcx()));
49
50     if cx.sess().asm_comments() {
51         add_span_comment(cx, s.span, s.repr(cx.tcx()).as_slice());
52     }
53
54     let mut bcx = cx;
55
56     let id = ast_util::stmt_id(s);
57     let cleanup_debug_loc =
58         debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(), id, s.span, false);
59     fcx.push_ast_cleanup_scope(cleanup_debug_loc);
60
61     match s.node {
62         ast::StmtExpr(ref e, _) | ast::StmtSemi(ref e, _) => {
63             bcx = trans_stmt_semi(bcx, &**e);
64         }
65         ast::StmtDecl(ref d, _) => {
66             match d.node {
67                 ast::DeclLocal(ref local) => {
68                     bcx = init_local(bcx, &**local);
69                     if cx.sess().opts.debuginfo == FullDebugInfo {
70                         trans::debuginfo::create_local_var_metadata(bcx,
71                                                                     &**local);
72                     }
73                 }
74                 // Inner items are visited by `trans_item`/`trans_meth`.
75                 ast::DeclItem(_) => {},
76             }
77         }
78         ast::StmtMac(..) => cx.tcx().sess.bug("unexpanded macro")
79     }
80
81     bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, ast_util::stmt_id(s));
82
83     return bcx;
84 }
85
86 pub fn trans_stmt_semi<'blk, 'tcx>(cx: Block<'blk, 'tcx>, e: &ast::Expr)
87                                    -> Block<'blk, 'tcx> {
88     let _icx = push_ctxt("trans_stmt_semi");
89     let ty = expr_ty(cx, e);
90     if ty::type_needs_drop(cx.tcx(), ty) {
91         expr::trans_to_lvalue(cx, e, "stmt").bcx
92     } else {
93         expr::trans_into(cx, e, expr::Ignore)
94     }
95 }
96
97 pub fn trans_block<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
98                                b: &ast::Block,
99                                mut dest: expr::Dest)
100                                -> Block<'blk, 'tcx> {
101     let _icx = push_ctxt("trans_block");
102     let fcx = bcx.fcx;
103     let mut bcx = bcx;
104
105     let cleanup_debug_loc =
106         debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(), b.id, b.span, true);
107     fcx.push_ast_cleanup_scope(cleanup_debug_loc);
108
109     for s in b.stmts.iter() {
110         bcx = trans_stmt(bcx, &**s);
111     }
112
113     if dest != expr::Ignore {
114         let block_ty = node_id_type(bcx, b.id);
115         if b.expr.is_none() || type_is_zero_size(bcx.ccx(), block_ty) {
116             dest = expr::Ignore;
117         }
118     }
119
120     match b.expr {
121         Some(ref e) => {
122             bcx = expr::trans_into(bcx, &**e, dest);
123         }
124         None => {
125             assert!(dest == expr::Ignore || bcx.unreachable.get());
126         }
127     }
128
129     bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, b.id);
130
131     return bcx;
132 }
133
134 pub fn trans_if<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
135                             if_id: ast::NodeId,
136                             cond: &ast::Expr,
137                             thn: &ast::Block,
138                             els: Option<&ast::Expr>,
139                             dest: expr::Dest)
140                             -> Block<'blk, 'tcx> {
141     debug!("trans_if(bcx={}, if_id={}, cond={}, thn={}, dest={})",
142            bcx.to_str(), if_id, bcx.expr_to_string(cond), thn.id,
143            dest.to_string(bcx.ccx()));
144     let _icx = push_ctxt("trans_if");
145     let mut bcx = bcx;
146
147     let cond_val = unpack_result!(bcx, expr::trans(bcx, cond).to_llbool());
148
149     // Drop branches that are known to be impossible
150     if is_const(cond_val) && !is_undef(cond_val) {
151         if const_to_uint(cond_val) == 1 {
152             match els {
153                 Some(elexpr) => {
154                     let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx };
155                     trans.visit_expr(&*elexpr);
156                 }
157                 None => {}
158             }
159             // if true { .. } [else { .. }]
160             bcx = trans_block(bcx, &*thn, dest);
161             trans::debuginfo::clear_source_location(bcx.fcx);
162         } else {
163             let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx } ;
164             trans.visit_block(&*thn);
165
166             match els {
167                 // if false { .. } else { .. }
168                 Some(elexpr) => {
169                     bcx = expr::trans_into(bcx, &*elexpr, dest);
170                     trans::debuginfo::clear_source_location(bcx.fcx);
171                 }
172
173                 // if false { .. }
174                 None => { }
175             }
176         }
177
178         return bcx;
179     }
180
181     let name = format!("then-block-{}-", thn.id);
182     let then_bcx_in = bcx.fcx.new_id_block(name.as_slice(), thn.id);
183     let then_bcx_out = trans_block(then_bcx_in, &*thn, dest);
184     trans::debuginfo::clear_source_location(bcx.fcx);
185
186     let next_bcx;
187     match els {
188         Some(elexpr) => {
189             let else_bcx_in = bcx.fcx.new_id_block("else-block", elexpr.id);
190             let else_bcx_out = expr::trans_into(else_bcx_in, &*elexpr, dest);
191             next_bcx = bcx.fcx.join_blocks(if_id,
192                                            &[then_bcx_out, else_bcx_out]);
193             CondBr(bcx, cond_val, then_bcx_in.llbb, else_bcx_in.llbb);
194         }
195
196         None => {
197             next_bcx = bcx.fcx.new_id_block("next-block", if_id);
198             Br(then_bcx_out, next_bcx.llbb);
199             CondBr(bcx, cond_val, then_bcx_in.llbb, next_bcx.llbb);
200         }
201     }
202
203     // Clear the source location because it is still set to whatever has been translated
204     // right before.
205     trans::debuginfo::clear_source_location(next_bcx.fcx);
206
207     next_bcx
208 }
209
210 pub fn trans_while<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
211                                loop_id: ast::NodeId,
212                                cond: &ast::Expr,
213                                body: &ast::Block)
214                                -> Block<'blk, 'tcx> {
215     let _icx = push_ctxt("trans_while");
216     let fcx = bcx.fcx;
217
218     //            bcx
219     //             |
220     //         cond_bcx_in  <--------+
221     //             |                 |
222     //         cond_bcx_out          |
223     //           |      |            |
224     //           |    body_bcx_in    |
225     // cleanup_blk      |            |
226     //    |           body_bcx_out --+
227     // next_bcx_in
228
229     let next_bcx_in = fcx.new_id_block("while_exit", loop_id);
230     let cond_bcx_in = fcx.new_id_block("while_cond", cond.id);
231     let body_bcx_in = fcx.new_id_block("while_body", body.id);
232
233     fcx.push_loop_cleanup_scope(loop_id, [next_bcx_in, cond_bcx_in]);
234
235     Br(bcx, cond_bcx_in.llbb);
236
237     // compile the block where we will handle loop cleanups
238     let cleanup_llbb = fcx.normal_exit_block(loop_id, cleanup::EXIT_BREAK);
239
240     // compile the condition
241     let Result {bcx: cond_bcx_out, val: cond_val} =
242         expr::trans(cond_bcx_in, cond).to_llbool();
243     CondBr(cond_bcx_out, cond_val, body_bcx_in.llbb, cleanup_llbb);
244
245     // loop body:
246     let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
247     Br(body_bcx_out, cond_bcx_in.llbb);
248
249     fcx.pop_loop_cleanup_scope(loop_id);
250     return next_bcx_in;
251 }
252
253 /// Translates a `for` loop.
254 pub fn trans_for<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
255                              loop_info: NodeInfo,
256                              pat: &ast::Pat,
257                              head: &ast::Expr,
258                              body: &ast::Block)
259                              -> Block<'blk, 'tcx> {
260     let _icx = push_ctxt("trans_for");
261
262     //            bcx
263     //             |
264     //      loopback_bcx_in  <-------+
265     //             |                 |
266     //      loopback_bcx_out         |
267     //           |      |            |
268     //           |    body_bcx_in    |
269     // cleanup_blk      |            |
270     //    |           body_bcx_out --+
271     // next_bcx_in
272
273     // Codegen the head to create the iterator value.
274     let iterator_datum =
275         unpack_datum!(bcx, expr::trans_to_lvalue(bcx, head, "for_head"));
276     let iterator_type = node_id_type(bcx, head.id);
277     debug!("iterator type is {}, datum type is {}",
278            ppaux::ty_to_string(bcx.tcx(), iterator_type),
279            ppaux::ty_to_string(bcx.tcx(), iterator_datum.ty));
280     let lliterator = load_ty(bcx, iterator_datum.val, iterator_datum.ty);
281
282     // Create our basic blocks and set up our loop cleanups.
283     let next_bcx_in = bcx.fcx.new_id_block("for_exit", loop_info.id);
284     let loopback_bcx_in = bcx.fcx.new_id_block("for_loopback", head.id);
285     let body_bcx_in = bcx.fcx.new_id_block("for_body", body.id);
286     bcx.fcx.push_loop_cleanup_scope(loop_info.id,
287                                     [next_bcx_in, loopback_bcx_in]);
288     Br(bcx, loopback_bcx_in.llbb);
289     let cleanup_llbb = bcx.fcx.normal_exit_block(loop_info.id,
290                                                  cleanup::EXIT_BREAK);
291
292     // Set up the method call (to `.next()`).
293     let method_call = MethodCall::expr(loop_info.id);
294     let method_type = (*loopback_bcx_in.tcx()
295                                      .method_map
296                                      .borrow())[method_call]
297                                      .ty;
298     let method_type = monomorphize_type(loopback_bcx_in, method_type);
299     let method_result_type = ty::ty_fn_ret(method_type).unwrap();
300     let option_cleanup_scope = body_bcx_in.fcx.push_custom_cleanup_scope();
301     let option_cleanup_scope_id = cleanup::CustomScope(option_cleanup_scope);
302
303     // Compile the method call (to `.next()`).
304     let mut loopback_bcx_out = loopback_bcx_in;
305     let option_datum =
306         unpack_datum!(loopback_bcx_out,
307                       datum::lvalue_scratch_datum(loopback_bcx_out,
308                                                   method_result_type,
309                                                   "loop_option",
310                                                   false,
311                                                   option_cleanup_scope_id,
312                                                   (),
313                                                   |(), bcx, lloption| {
314         let Result {
315             bcx,
316             val: _
317         } = callee::trans_call_inner(bcx,
318                                      Some(loop_info),
319                                      method_type,
320                                      |bcx, arg_cleanup_scope| {
321                                          meth::trans_method_callee(
322                                              bcx,
323                                              method_call,
324                                              None,
325                                              arg_cleanup_scope)
326                                      },
327                                      callee::ArgVals(&[lliterator]),
328                                      Some(expr::SaveIn(lloption)));
329         bcx
330     }));
331
332     // Check the discriminant; if the `None` case, exit the loop.
333     let option_representation = adt::represent_type(loopback_bcx_out.ccx(),
334                                                     method_result_type);
335     let lldiscriminant = adt::trans_get_discr(loopback_bcx_out,
336                                               &*option_representation,
337                                               option_datum.val,
338                                               None);
339     let i1_type = Type::i1(loopback_bcx_out.ccx());
340     let llcondition = Trunc(loopback_bcx_out, lldiscriminant, i1_type);
341     CondBr(loopback_bcx_out, llcondition, body_bcx_in.llbb, cleanup_llbb);
342
343     // Now we're in the body. Unpack the `Option` value into the programmer-
344     // supplied pattern.
345     let llpayload = adt::trans_field_ptr(body_bcx_in,
346                                          &*option_representation,
347                                          option_datum.val,
348                                          1,
349                                          0);
350     let binding_cleanup_scope = body_bcx_in.fcx.push_custom_cleanup_scope();
351     let binding_cleanup_scope_id =
352         cleanup::CustomScope(binding_cleanup_scope);
353     let mut body_bcx_out =
354         _match::store_for_loop_binding(body_bcx_in,
355                                        pat,
356                                        llpayload,
357                                        binding_cleanup_scope_id);
358
359     // Codegen the body.
360     body_bcx_out = trans_block(body_bcx_out, body, expr::Ignore);
361     body_bcx_out =
362         body_bcx_out.fcx
363                     .pop_and_trans_custom_cleanup_scope(body_bcx_out,
364                                                         binding_cleanup_scope);
365     body_bcx_out =
366         body_bcx_out.fcx
367                     .pop_and_trans_custom_cleanup_scope(body_bcx_out,
368                                                         option_cleanup_scope);
369     Br(body_bcx_out, loopback_bcx_in.llbb);
370
371     // Codegen cleanups and leave.
372     next_bcx_in.fcx.pop_loop_cleanup_scope(loop_info.id);
373     next_bcx_in
374 }
375
376 pub fn trans_loop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
377                               loop_id: ast::NodeId,
378                               body: &ast::Block)
379                               -> Block<'blk, 'tcx> {
380     let _icx = push_ctxt("trans_loop");
381     let fcx = bcx.fcx;
382
383     //            bcx
384     //             |
385     //         body_bcx_in
386     //             |
387     //         body_bcx_out
388     //
389     // next_bcx
390     //
391     // Links between body_bcx_in and next_bcx are created by
392     // break statements.
393
394     let next_bcx_in = bcx.fcx.new_id_block("loop_exit", loop_id);
395     let body_bcx_in = bcx.fcx.new_id_block("loop_body", body.id);
396
397     fcx.push_loop_cleanup_scope(loop_id, [next_bcx_in, body_bcx_in]);
398
399     Br(bcx, body_bcx_in.llbb);
400     let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
401     Br(body_bcx_out, body_bcx_in.llbb);
402
403     fcx.pop_loop_cleanup_scope(loop_id);
404
405     return next_bcx_in;
406 }
407
408 pub fn trans_break_cont<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
409                                     expr_id: ast::NodeId,
410                                     opt_label: Option<Ident>,
411                                     exit: uint)
412                                     -> Block<'blk, 'tcx> {
413     let _icx = push_ctxt("trans_break_cont");
414     let fcx = bcx.fcx;
415
416     if bcx.unreachable.get() {
417         return bcx;
418     }
419
420     // Locate loop that we will break to
421     let loop_id = match opt_label {
422         None => fcx.top_loop_scope(),
423         Some(_) => {
424             match bcx.tcx().def_map.borrow().get(&expr_id) {
425                 Some(&def::DefLabel(loop_id)) => loop_id,
426                 ref r => {
427                     bcx.tcx().sess.bug(format!("{} in def-map for label",
428                                                r).as_slice())
429                 }
430             }
431         }
432     };
433
434     // Generate appropriate cleanup code and branch
435     let cleanup_llbb = fcx.normal_exit_block(loop_id, exit);
436     Br(bcx, cleanup_llbb);
437     Unreachable(bcx); // anything afterwards should be ignored
438     return bcx;
439 }
440
441 pub fn trans_break<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
442                                expr_id: ast::NodeId,
443                                label_opt: Option<Ident>)
444                                -> Block<'blk, 'tcx> {
445     return trans_break_cont(bcx, expr_id, label_opt, cleanup::EXIT_BREAK);
446 }
447
448 pub fn trans_cont<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
449                               expr_id: ast::NodeId,
450                               label_opt: Option<Ident>)
451                               -> Block<'blk, 'tcx> {
452     return trans_break_cont(bcx, expr_id, label_opt, cleanup::EXIT_LOOP);
453 }
454
455 pub fn trans_ret<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
456                              e: Option<&ast::Expr>)
457                              -> Block<'blk, 'tcx> {
458     let _icx = push_ctxt("trans_ret");
459     let fcx = bcx.fcx;
460     let mut bcx = bcx;
461     let dest = match (fcx.llretslotptr.get(), e) {
462         (Some(_), Some(e)) => {
463             let ret_ty = expr_ty(bcx, &*e);
464             expr::SaveIn(fcx.get_ret_slot(bcx, ty::FnConverging(ret_ty), "ret_slot"))
465         }
466         _ => expr::Ignore,
467     };
468     if let Some(x) = e {
469         bcx = expr::trans_into(bcx, &*x, dest);
470         match dest {
471             expr::SaveIn(slot) if fcx.needs_ret_allocas => {
472                 Store(bcx, slot, fcx.llretslotptr.get().unwrap());
473             }
474             _ => {}
475         }
476     }
477     let cleanup_llbb = fcx.return_exit_block();
478     Br(bcx, cleanup_llbb);
479     Unreachable(bcx);
480     return bcx;
481 }
482
483 pub fn trans_fail<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
484                               sp: Span,
485                               fail_str: InternedString)
486                               -> Block<'blk, 'tcx> {
487     let ccx = bcx.ccx();
488     let _icx = push_ctxt("trans_fail_value");
489
490     let v_str = C_str_slice(ccx, fail_str);
491     let loc = bcx.sess().codemap().lookup_char_pos(sp.lo);
492     let filename = token::intern_and_get_ident(loc.file.name.as_slice());
493     let filename = C_str_slice(ccx, filename);
494     let line = C_uint(ccx, loc.line);
495     let expr_file_line_const = C_struct(ccx, &[v_str, filename, line], false);
496     let expr_file_line = consts::const_addr_of(ccx, expr_file_line_const, ast::MutImmutable);
497     let args = vec!(expr_file_line);
498     let did = langcall(bcx, Some(sp), "", PanicFnLangItem);
499     let bcx = callee::trans_lang_call(bcx,
500                                       did,
501                                       args.as_slice(),
502                                       Some(expr::Ignore)).bcx;
503     Unreachable(bcx);
504     return bcx;
505 }
506
507 pub fn trans_fail_bounds_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
508                                            sp: Span,
509                                            index: ValueRef,
510                                            len: ValueRef)
511                                            -> Block<'blk, 'tcx> {
512     let ccx = bcx.ccx();
513     let _icx = push_ctxt("trans_fail_bounds_check");
514
515     // Extract the file/line from the span
516     let loc = bcx.sess().codemap().lookup_char_pos(sp.lo);
517     let filename = token::intern_and_get_ident(loc.file.name.as_slice());
518
519     // Invoke the lang item
520     let filename = C_str_slice(ccx,  filename);
521     let line = C_uint(ccx, loc.line);
522     let file_line_const = C_struct(ccx, &[filename, line], false);
523     let file_line = consts::const_addr_of(ccx, file_line_const, ast::MutImmutable);
524     let args = vec!(file_line, index, len);
525     let did = langcall(bcx, Some(sp), "", PanicBoundsCheckFnLangItem);
526     let bcx = callee::trans_lang_call(bcx,
527                                       did,
528                                       args.as_slice(),
529                                       Some(expr::Ignore)).bcx;
530     Unreachable(bcx);
531     return bcx;
532 }