1#   Copyright (C) 1997-2018 Free Software Foundation, Inc.
2
3# This program is free software; you can redistribute it and/or modify
4# it under the terms of the GNU General Public License as published by
5# the Free Software Foundation; either version 3 of the License, or
6# (at your option) any later version.
7#
8# This program is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11# GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License
14# along with GCC; see the file COPYING3.  If not see
15# <http://www.gnu.org/licenses/>.
16
17load_lib dg.exp
18load_lib file-format.exp
19load_lib target-supports.exp
20load_lib target-supports-dg.exp
21load_lib scanasm.exp
22load_lib scanrtl.exp
23load_lib scantree.exp
24load_lib scanipa.exp
25load_lib scanlang.exp
26load_lib timeout.exp
27load_lib timeout-dg.exp
28load_lib prune.exp
29load_lib libgloss.exp
30load_lib target-libpath.exp
31load_lib torture-options.exp
32load_lib fortran-modules.exp
33load_lib multiline.exp
34
35# We set LC_ALL and LANG to C so that we get the same error messages as expected.
36setenv LC_ALL C
37setenv LANG C
38
39# Many hosts now default to a non-ASCII C locale, however, so
40# they can set a charset encoding here if they need.
41if { [ishost "*-*-cygwin*"] } {
42  setenv LC_ALL C.ASCII
43  setenv LANG C.ASCII
44}
45
46# Avoid sporadic data-losses with expect
47match_max -d 10000
48
49# Ensure GCC_COLORS is unset, for the rare testcases that verify
50# how output is colorized.
51if [info exists ::env(GCC_COLORS) ] {
52    unsetenv GCC_COLORS
53}
54
55global GCC_UNDER_TEST
56if ![info exists GCC_UNDER_TEST] {
57    set GCC_UNDER_TEST "[find_gcc]"
58}
59
60# This file may be sourced, so don't override environment settings
61# that have been previously setup.
62if { $orig_environment_saved == 0 } {
63    append ld_library_path [gcc-set-multilib-library-path $GCC_UNDER_TEST]
64    set_ld_library_path_env_vars
65}
66
67# Some torture-options cause intermediate code output, unusable for
68# testing using e.g. scan-assembler.  In this variable are the options
69# how to force it, when needed.
70global gcc_force_conventional_output
71set gcc_force_conventional_output ""
72
73set LTO_TORTURE_OPTIONS ""
74if [info exists TORTURE_OPTIONS] {
75    set DG_TORTURE_OPTIONS $TORTURE_OPTIONS
76} else {
77    # It is theoretically beneficial to group all of the O2/O3 options together,
78    # as in many cases the compiler will generate identical executables for
79    # all of them--and the c-torture testsuite will skip testing identical
80    # executables multiple times.
81    # Also note that -finline-functions is explicitly included in one of the
82    # items below, even though -O3 is also specified, because some ports may
83    # choose to disable inlining functions by default, even when optimizing.
84    set DG_TORTURE_OPTIONS [list \
85	{ -O0 } \
86	{ -O1 } \
87	{ -O2 } \
88	{ -O3 -fomit-frame-pointer -funroll-loops -fpeel-loops -ftracer -finline-functions } \
89	{ -O3 -g } \
90	{ -Os } ]
91
92    if [check_effective_target_lto] {
93        # When having plugin test both slim and fat LTO and plugin/nonplugin
94        # path.
95	if [check_linker_plugin_available] {
96           set LTO_TORTURE_OPTIONS [list \
97	      { -O2 -flto -fno-use-linker-plugin -flto-partition=none } \
98	      { -O2 -flto -fuse-linker-plugin -fno-fat-lto-objects }
99           ]
100        } else {
101           set LTO_TORTURE_OPTIONS [list \
102	      { -O2 -flto -flto-partition=none } \
103	      { -O2 -flto }
104           ]
105        }
106        set gcc_force_conventional_output "-ffat-lto-objects"
107    }
108}
109
110if [info exists ADDITIONAL_TORTURE_OPTIONS] {
111    set DG_TORTURE_OPTIONS \
112	[concat $DG_TORTURE_OPTIONS $ADDITIONAL_TORTURE_OPTIONS]
113}
114
115global orig_environment_saved
116
117# Deduce generated files from tool flags, return finalcode string
118proc schedule-cleanups { opts } {
119    global additional_sources
120    set finalcode ""
121    set testcases {}
122    lappend testcases [lindex [testname-for-summary] 0]
123    verbose "Cleanup testcases: $testcases" 4
124    if { [info exists additional_sources] && $additional_sources != "" } {
125	lappend testcases $additional_sources
126	verbose "Cleanup testcases, additional: $additional_sources" 4
127    }
128    verbose "Cleanup all options: $opts" 4
129
130    # First some fixups to transform stuff to something manageable ..
131    # --dump= should translate to -d with joined operand.
132    if [regexp -- {(^|\s+)--dump=[^\s]+(\s+|$)} $opts] {
133	regsub -all -- {--dump=} $opts {-d} opts
134    }
135    # -da and -dx are treated as shorthand for -fdump-rtl-all here
136    if [regexp -- {(^|\s+)-d[ax](\s+|$)} $opts] {
137	verbose "Cleanup -d seen" 4
138	lappend opts "-fdump-rtl-all"
139    }
140    # .. and don't question why there is --dump=? and -d?
141
142    # Then handle options that generate non-dump files
143    # TODO
144    # -fprofile-generate -> cleanup-coverage-files()
145    # -fstack-usage -> cleanup-stack-usage()
146    if [regexp -- {(^|\s+)-fstack-usage(\s+|$)} $opts] {
147	verbose "Cleanup -fstack-usage seen" 4
148#	append finalcode "cleanup-stack-usage\n"
149    }
150    global keep_saved_temps_suffixes
151    if [info exists keep_saved_temps_suffixes ] {
152	verbose "dg-keep-saved-temps ${keep_saved_temps_suffixes}" 2
153    }
154    # -save-temps -> cleanup-saved-temps()
155    if [regexp -- {(^|\s+)-save-temps(\s+|$)} $opts] {
156	verbose "Cleanup -save-temps seen" 4
157	if [info exists keep_saved_temps_suffixes] {
158	    append finalcode "cleanup-saved-temps ${keep_saved_temps_suffixes}\n"
159	} else {
160	    append finalcode "cleanup-saved-temps\n"
161	}
162    } else {
163	if [info exists keep_saved_temps_suffixes ] {
164	    error "dg-keep-saved-temps specified but testcase does not -save-temps"
165	    return
166	}
167    }
168    # Finally see if there are any dumps in opts, otherwise we are done
169    if [regexp -- {(?=(?:^|[ \t]+)?)-fdump-[^ \t]+(?=(?:$|[ \t]+)?)} $opts] {
170        # Lang, Ipa, Rtl, Tree for simplicity
171        set ptn "{l,i,r,t}"
172    } else {
173        return $finalcode
174    }
175    # stem.ext.<passnum><fam>.<passname><pass-instances>
176    # (tree)passes can have multiple instances, thus optional trailing *
177    set ptn "\[0-9\]\[0-9\]\[0-9\]$ptn.*"
178    # Handle ltrans files around -flto
179    if [regexp -- {(^|\s+)-flto(\s+|$)} $opts] {
180	verbose "Cleanup -flto seen" 4
181	set ltrans "{ltrans\[0-9\]*.,}"
182    } else {
183	set ltrans ""
184    }
185    set ptn "$ltrans$ptn"
186    verbose "Cleanup final ptn: $ptn" 4
187    set tfiles {}
188    foreach src $testcases {
189	set basename [file tail $src]
190	if { $ltrans != "" } {
191	    # ??? should we use upvar 1 output_file instead of this (dup ?)
192	    set stem [file rootname $basename]
193	    set basename_ext [file extension $basename]
194	    if {$basename_ext != ""} {
195		regsub -- {^.*\.} $basename_ext {} basename_ext
196	    }
197	    lappend tfiles "$stem.{$basename_ext,exe}"
198	    unset basename_ext
199	} else {
200	    lappend tfiles $basename
201	}
202    }
203    if { [llength $tfiles] > 1 } {
204	set tfiles [join $tfiles ","]
205	set tfiles "{$tfiles}"
206    }
207    verbose "Cleanup final testcases: $tfiles" 4
208    # We have to quote the regex
209    regsub -all {([][$^?+*()|\\{}])} "$tfiles.$ptn" {\\\1} ptn
210    set final ""
211    append final {remove-build-file }
212    append final "\"$ptn\""
213    verbose "Cleanup final: $final" 4
214    append finalcode "$final\n"
215
216    return $finalcode
217}
218
219# Define gcc callbacks for dg.exp.
220
221proc gcc-dg-test-1 { target_compile prog do_what extra_tool_flags } {
222    # Set up the compiler flags, based on what we're going to do.
223
224    set options [list]
225
226    # Tests should be able to use "dg-do repo".  However, the dg test
227    # driver checks the argument to dg-do against a list of acceptable
228    # options, and "repo" is not among them.  Therefore, we resort to
229    # this ugly approach.
230    if [string match "*-frepo*" $extra_tool_flags] then {
231	set do_what "repo"
232    }
233
234    switch $do_what {
235	"preprocess" {
236	    set compile_type "preprocess"
237	    set output_file "[file rootname [file tail $prog]].i"
238	}
239	"compile" {
240	    set compile_type "assembly"
241	    set output_file "[file rootname [file tail $prog]].s"
242	}
243	"assemble" {
244	    set compile_type "object"
245	    set output_file "[file rootname [file tail $prog]].o"
246	}
247	"precompile" {
248	    set compile_type "precompiled_header"
249	    set output_file "[file tail $prog].gch"
250	}
251	"link" {
252	    set compile_type "executable"
253	    set output_file "[file rootname [file tail $prog]].exe"
254	    # The following line is needed for targets like the i960 where
255	    # the default output file is b.out.  Sigh.
256	}
257	"repo" {
258	    set compile_type "object"
259	    set output_file "[file rootname [file tail $prog]].o"
260	}
261	"run" {
262	    set compile_type "executable"
263	    # FIXME: "./" is to cope with "." not being in $PATH.
264	    # Should this be handled elsewhere?
265	    # YES.
266	    set output_file "./[file rootname [file tail $prog]].exe"
267	    # This is the only place where we care if an executable was
268	    # created or not.  If it was, dg.exp will try to run it.
269	    catch { remote_file build delete $output_file }
270	}
271	default {
272	    perror "$do_what: not a valid dg-do keyword"
273	    return ""
274	}
275    }
276
277    # Let { dg-final { action } } force options as returned by an
278    # optional proc ${action}_required_options.
279    upvar 2 dg-final-code finalcode
280    foreach x [split $finalcode "\n"] {
281	set finalcmd [lindex $x 0]
282	if { [info procs ${finalcmd}_required_options] != "" } {
283	    set req [${finalcmd}_required_options]
284	    if { $req != "" && [lsearch -exact $extra_tool_flags $req] == -1 } {
285		lappend extra_tool_flags $req
286	    }
287	}
288    }
289
290    append finalcode [schedule-cleanups "$options $extra_tool_flags"]
291    if { $extra_tool_flags != "" } {
292	lappend options "additional_flags=$extra_tool_flags"
293    }
294
295    verbose "$target_compile $prog $output_file $compile_type $options" 4
296    set comp_output [$target_compile "$prog" "$output_file" "$compile_type" $options]
297
298    # Look for an internal compiler error, which sometimes masks the fact
299    # that we didn't get an expected error message.  XFAIL an ICE via
300    # dg-xfail-if and use { dg-prune-output ".*internal compiler error.*" }
301    # to avoid a second failure for excess errors.
302    if [string match "*internal compiler error*" $comp_output] {
303	upvar 2 name name
304	fail "$name (internal compiler error)"
305    }
306
307    if { $do_what == "repo" } {
308	set object_file "$output_file"
309	set output_file "[file rootname [file tail $prog]].exe"
310	set comp_output \
311	    [ concat $comp_output \
312		  [$target_compile "$object_file" "$output_file" \
313		       "executable" $options] ]
314    }
315
316    return [list $comp_output $output_file]
317}
318
319proc gcc-dg-test { prog do_what extra_tool_flags } {
320    return [gcc-dg-test-1 gcc_target_compile $prog $do_what $extra_tool_flags]
321}
322
323# Global: should blank lines be allowed in the output?
324# By default, they should not be.  (PR other/69006)
325# However, there are some ways for them to validly occur.
326set allow_blank_lines 0
327
328# A command for use by testcases to mark themselves as expecting
329# blank lines in the output.
330
331proc dg-allow-blank-lines-in-output { args } {
332    global allow_blank_lines
333    set allow_blank_lines 1
334}
335
336proc gcc-dg-prune { system text } {
337    global additional_prunes
338
339    # Extra prune rules that will apply to tests defined in a .exp file.
340    # Always remember to clear it in .exp file after executed all tests.
341    global dg_runtest_extra_prunes
342
343    # Complain about blank lines in the output (PR other/69006)
344    global allow_blank_lines
345    if { !$allow_blank_lines } {
346	set num_blank_lines [llength [regexp -all -inline "\n\n" $text]]
347	if { $num_blank_lines } {
348	    global testname_with_flags
349	    fail "$testname_with_flags $num_blank_lines blank line(s) in output"
350	}
351	set allow_blank_lines 0
352    }
353
354    set text [prune_gcc_output $text]
355
356    foreach p "$additional_prunes $dg_runtest_extra_prunes" {
357	if { [string length $p] > 0 } {
358	    # Following regexp matches a complete line containing $p.
359	    regsub -all "(^|\n)\[^\n\]*$p\[^\n\]*" $text "" text
360	}
361    }
362
363    # If we see "region xxx is full" then the testcase is too big for ram.
364    # This is tricky to deal with in a large testsuite like c-torture so
365    # deal with it here.  Just mark the testcase as unsupported.
366    if [regexp "(^|\n)\[^\n\]*: region \[^\n\]* is full" $text] {
367	# The format here is important.  See dg.exp.
368	return "::unsupported::memory full"
369    }
370
371    if { [regexp "(^|\n)\[^\n\]*: relocation truncated to fit" $text]
372          && [check_effective_target_tiny] } {
373        return "::unsupported::memory full"
374    }
375
376    # Likewise, if we see ".text exceeds local store range" or
377    # similar.
378    if {[string match "spu-*" $system] && \
379	    [string match "*exceeds local store*" $text]} {
380	# The format here is important.  See dg.exp.
381	return "::unsupported::memory full"
382    }
383
384    return $text
385}
386
387# Replace ${tool}_load with a wrapper to provide for an expected nonzero
388# exit status.  Multiple languages include this file so this handles them
389# all, not just gcc.
390if { [info procs ${tool}_load] != [list] \
391      && [info procs saved_${tool}_load] == [list] } {
392    rename ${tool}_load saved_${tool}_load
393
394    proc ${tool}_load { program args } {
395	global tool
396	global shouldfail
397	global set_target_env_var
398
399	set saved_target_env_var [list]
400	if { [info exists set_target_env_var] \
401	     && [llength $set_target_env_var] != 0 } {
402	    if { [is_remote target] } {
403		return [list "unsupported" ""]
404	    }
405	    set-target-env-var
406	}
407	set result [eval [list saved_${tool}_load $program] $args]
408	if { [info exists set_target_env_var] \
409	     && [llength $set_target_env_var] != 0 } {
410	    restore-target-env-var
411	}
412	if { $shouldfail != 0 } {
413	    switch [lindex $result 0] {
414		"pass" { set status "fail" }
415		"fail" { set status "pass" }
416		default { set status [lindex $result 0] }
417	    }
418	    set result [list $status [lindex $result 1]]
419	}
420
421	set result [list [lindex $result 0] [prune_file_path [lindex $result 1]]]
422	return $result
423    }
424}
425
426proc dg-set-target-env-var { args } {
427    global set_target_env_var
428    if { [llength $args] != 3 } {
429	error "dg-set-target-env-var: need two arguments"
430	return
431    }
432    lappend set_target_env_var [list [lindex $args 1] [lindex $args 2]]
433}
434
435proc set-target-env-var { } {
436    global set_target_env_var
437    upvar 1 saved_target_env_var saved_target_env_var
438    foreach env_var $set_target_env_var {
439	set var [lindex $env_var 0]
440	set value [lindex $env_var 1]
441	if [info exists ::env($var)] {
442	    lappend saved_target_env_var [list $var 1 $::env($var)]
443	} else {
444	    lappend saved_target_env_var [list $var 0]
445	}
446	setenv $var $value
447    }
448}
449
450proc restore-target-env-var { } {
451    upvar 1 saved_target_env_var saved_target_env_var
452    for { set env_vari [llength $saved_target_env_var] } {
453          [incr env_vari -1] >= 0 } {} {
454	set env_var [lindex $saved_target_env_var $env_vari]
455	set var [lindex $env_var 0]
456	if [lindex $env_var 1] {
457	    setenv $var [lindex $env_var 2]
458	} else {
459	    unsetenv $var
460	}
461    }
462}
463
464proc dg-set-compiler-env-var { args } {
465    global set_compiler_env_var
466    global saved_compiler_env_var
467    if { [llength $args] != 3 } {
468	error "dg-set-compiler-env-var: need two arguments"
469	return
470    }
471    set var [lindex $args 1]
472    set value [lindex $args 2]
473    if [info exists ::env($var)] {
474      lappend saved_compiler_env_var [list $var 1 $::env($var)]
475    } else {
476      lappend saved_compiler_env_var [list $var 0]
477    }
478    setenv $var $value
479    lappend set_compiler_env_var [list $var $value]
480}
481
482proc restore-compiler-env-var { } {
483    global saved_compiler_env_var
484    for { set env_vari [llength $saved_compiler_env_var] } {
485          [incr env_vari -1] >= 0 } {} {
486	set env_var [lindex $saved_compiler_env_var $env_vari]
487	set var [lindex $env_var 0]
488	if [lindex $env_var 1] {
489	    setenv $var [lindex $env_var 2]
490	} else {
491	    unsetenv $var
492	}
493    }
494}
495
496# Utility routines.
497
498#
499# search_for -- looks for a string match in a file
500#
501proc search_for { file pattern } {
502    set fd [open $file r]
503    while { [gets $fd cur_line]>=0 } {
504	if [string match "*$pattern*" $cur_line] then {
505	    close $fd
506	    return 1
507	}
508    }
509    close $fd
510    return 0
511}
512
513# Modified dg-runtest that can cycle through a list of optimization options
514# as c-torture does.
515proc gcc-dg-runtest { testcases flags default-extra-flags } {
516    global runtests
517
518    # Some callers set torture options themselves; don't override those.
519    set existing_torture_options [torture-options-exist]
520    if { $existing_torture_options == 0 } {
521	global DG_TORTURE_OPTIONS LTO_TORTURE_OPTIONS
522	torture-init
523	set-torture-options $DG_TORTURE_OPTIONS [list {}] $LTO_TORTURE_OPTIONS
524    }
525    dump-torture-options
526
527    foreach test $testcases {
528	global torture_with_loops torture_without_loops
529	# If we're only testing specific files and this isn't one of
530	# them, skip it.
531	if ![runtest_file_p $runtests $test] {
532	    continue
533        }
534
535	# Look for a loop within the source code - if we don't find one,
536	# don't pass -funroll[-all]-loops.
537	if [expr [search_for $test "for*("]+[search_for $test "while*("]] {
538	    set option_list $torture_with_loops
539	} else {
540	    set option_list $torture_without_loops
541	}
542
543	set nshort [file tail [file dirname $test]]/[file tail $test]
544
545	foreach flags_t $option_list {
546	    global torture_current_flags
547	    set torture_current_flags "$flags_t"
548	    verbose "Testing $nshort, $flags $flags_t" 1
549	    dg-test $test "$flags $flags_t" ${default-extra-flags}
550	}
551    }
552
553    if { $existing_torture_options == 0 } {
554	torture-finish
555    }
556}
557
558proc gcc-dg-debug-runtest { target_compile trivial opt_opts testcases } {
559    global srcdir subdir
560
561    if ![info exists DEBUG_TORTURE_OPTIONS] {
562	set DEBUG_TORTURE_OPTIONS ""
563	foreach type {-gdwarf-2 -gstabs -gstabs+ -gxcoff -gxcoff+} {
564	    set comp_output [$target_compile \
565		    "$srcdir/$subdir/$trivial" "trivial.S" assembly \
566		    "additional_flags=$type"]
567	    if { ! [string match "*: target system does not support the * debug format*" \
568		    $comp_output] } {
569		remove-build-file "trivial.S"
570		foreach level {1 "" 3} {
571		    if { ($type == "-gdwarf-2") && ($level != "") } {
572			lappend DEBUG_TORTURE_OPTIONS [list "${type}" "-g${level}"]
573			foreach opt $opt_opts {
574			    lappend DEBUG_TORTURE_OPTIONS \
575				    [list "${type}" "-g${level}" "$opt" ]
576			}
577		    } else {
578			lappend DEBUG_TORTURE_OPTIONS [list "${type}${level}"]
579			foreach opt $opt_opts {
580			    lappend DEBUG_TORTURE_OPTIONS \
581				    [list "${type}${level}" "$opt" ]
582			}
583		    }
584		}
585	    }
586	}
587    }
588
589    verbose -log "Using options $DEBUG_TORTURE_OPTIONS"
590
591    global runtests
592
593    foreach test $testcases {
594	# If we're only testing specific files and this isn't one of
595	# them, skip it.
596	if ![runtest_file_p $runtests $test] {
597	    continue
598	}
599
600	set nshort [file tail [file dirname $test]]/[file tail $test]
601
602	foreach flags $DEBUG_TORTURE_OPTIONS {
603	    set doit 1
604
605	    # These tests check for information which may be deliberately
606	    # suppressed at -g1.
607	    if { ([string match {*/debug-[126].c} "$nshort"] \
608		   || [string match {*/enum-1.c} "$nshort"] \
609		   || [string match {*/enum-[12].C} "$nshort"]) \
610		    && ([string match "*1" [lindex "$flags" 0] ]
611			|| [lindex "$flags" 1] == "-g1") } {
612		set doit 0
613	    }
614
615    # High optimization can remove the variable whose existence is tested.
616    # Dwarf debugging with commentary (-dA) preserves the symbol name in the
617    # assembler output, but stabs debugging does not.
618    # http://gcc.gnu.org/ml/gcc-regression/2003-04/msg00095.html
619	    if { [string match {*/debug-[12].c} "$nshort"] \
620		    && [string match "*O*" "$flags"] \
621		    && ( [string match "*coff*" "$flags"] \
622			 || [string match "*stabs*" "$flags"] ) } {
623		set doit 0
624	    }
625
626	    if { $doit } {
627		verbose -log "Testing $nshort, $flags" 1
628		dg-test $test $flags ""
629	    }
630	}
631    }
632}
633
634# Prune any messages matching ARGS[1] (a regexp) from test output.
635proc dg-prune-output { args } {
636    global additional_prunes
637
638    if { [llength $args] != 2 } {
639	error "[lindex $args 1]: need one argument"
640	return
641    }
642
643    lappend additional_prunes [lindex $args 1]
644}
645
646# Remove files matching the pattern from the build machine.
647proc remove-build-file { pat } {
648    verbose "remove-build-file `$pat'" 2
649    set file_list "[glob -nocomplain $pat]"
650    verbose "remove-build-file `$file_list'" 2
651    foreach output_file $file_list {
652	if [is_remote host] {
653	    # Ensure the host knows the file is gone by deleting there
654	    # first.
655	    remote_file host delete $output_file
656	}
657	remote_file build delete $output_file
658    }
659}
660
661# Remove runtime-generated profile file for the current test.
662proc cleanup-profile-file { } {
663    remove-build-file "mon.out"
664    remove-build-file "gmon.out"
665}
666
667# Remove compiler-generated coverage files for the current test.
668proc cleanup-coverage-files { } {
669    global additional_sources_used
670    set testcase [testname-for-summary]
671    # The name might include a list of options; extract the file name.
672    set testcase [lindex $testcase 0]
673    remove-build-file "[file rootname [file tail $testcase]].gc??"
674
675    # Clean up coverage files for additional source files.
676    if [info exists additional_sources_used] {
677	foreach srcfile $additional_sources_used {
678	    remove-build-file "[file rootname [file tail $srcfile]].gc??"
679	}
680    }
681}
682
683# Remove compiler-generated files from -repo for the current test.
684proc cleanup-repo-files { } {
685    global additional_sources_used
686    set testcase [testname-for-summary]
687    # The name might include a list of options; extract the file name.
688    set testcase [lindex $testcase 0]
689    remove-build-file "[file rootname [file tail $testcase]].o"
690    remove-build-file "[file rootname [file tail $testcase]].rpo"
691
692    # Clean up files for additional source files.
693    if [info exists additional_sources_used] {
694	foreach srcfile $additional_sources_used {
695	    remove-build-file "[file rootname [file tail $srcfile]].o"
696	    remove-build-file "[file rootname [file tail $srcfile]].rpo"
697	}
698    }
699}
700
701# Remove a final insns dump file for the current test.
702proc cleanup-final-insns-dump { } {
703    set testcase [testname-for-summary]
704    # The name might include a list of options; extract the file name.
705    set testcase [lindex $testcase 0]
706    remove-build-file "[file rootname [file tail $testcase]].s.gkd"
707
708    # Clean up files for additional source files.
709    if [info exists additional_sources_used] {
710	foreach srcfile $additional_sources_used {
711	    remove-build-file "[file rootname [file tail $srcfile]].s.gkd"
712	}
713    }
714}
715
716# Remove a stack usage file for the current test.
717proc cleanup-stack-usage { } {
718    set testcase [testname-for-summary]
719    # The name might include a list of options; extract the file name.
720    set testcase [lindex $testcase 0]
721    remove-build-file "[file rootname [file tail $testcase]].su"
722
723    # Clean up files for additional source files.
724    if [info exists additional_sources_used] {
725	foreach srcfile $additional_sources_used {
726	    remove-build-file "[file rootname [file tail $srcfile]].su"
727	}
728    }
729}
730
731# Remove an Ada spec file for the current test.
732proc cleanup-ada-spec { } {
733    global additional_sources_used
734    set testcase [testname-for-summary]
735    remove-build-file "[get_ada_spec_filename $testcase]"
736
737    # Clean up files for additional source files.
738    if [info exists additional_sources_used] {
739	foreach srcfile $additional_sources_used {
740	    remove-build-file "[get_ada_spec_filename $srcfile]"
741	}
742    }
743}
744
745# Remove files kept by --save-temps for the current test.
746#
747# Currently this is only .i, .ii, .s and .o files, but more can be added
748# if there are tests generating them.
749# ARGS is a list of suffixes to NOT delete.
750proc cleanup-saved-temps { args } {
751    global additional_sources_used
752    set suffixes {}
753
754    # add the to-be-kept suffixes
755    foreach suffix {".mii" ".ii" ".i" ".s" ".o" ".gkd" ".res" ".ltrans.out"} {
756	if {[lsearch $args $suffix] < 0} {
757	    lappend suffixes $suffix
758	}
759    }
760
761    set testcase [testname-for-summary]
762    # The name might include a list of options; extract the file name.
763    set testcase [lindex $testcase 0]
764    foreach suffix $suffixes {
765	remove-build-file "[file rootname [file tail $testcase]]$suffix"
766	remove-build-file "[file rootname [file tail $testcase]].exe$suffix"
767	remove-build-file "[file rootname [file tail $testcase]].exe.ltrans\[0-9\]*$suffix"
768	# -fcompare-debug dumps
769	remove-build-file "[file rootname [file tail $testcase]].gk$suffix"
770    }
771
772    # Clean up saved temp files for additional source files.
773    if [info exists additional_sources_used] {
774	foreach srcfile $additional_sources_used {
775	    foreach suffix $suffixes {
776		remove-build-file "[file rootname [file tail $srcfile]]$suffix"
777		remove-build-file "[file rootname [file tail $srcfile]].exe$suffix"
778		remove-build-file "[file rootname [file tail $srcfile]].exe.ltrans\[0-9\]*$suffix"
779
780		# -fcompare-debug dumps
781		remove-build-file "[file rootname [file tail $srcfile]].gk$suffix"
782	    }
783	}
784    }
785}
786
787
788# Files to be kept after cleanup of --save-temps for the current test.
789# ARGS is a list of suffixes to NOT delete.
790proc dg-keep-saved-temps { args } {
791    global keep_saved_temps_suffixes
792    set keep_saved_temps_suffixes {}
793
794    # add the to-be-kept suffixes
795    foreach suffix {".mii" ".ii" ".i" ".s" ".o" ".gkd" ".res" ".ltrans.out"} {
796	if {[lsearch $args $suffix] >= 0} {
797	    lappend keep_saved_temps_suffixes $suffix
798	}
799    }
800    if { [llength keep_saved_temps_suffixes] < 1 } {
801	error "dg-keep-saved-temps ${args} did not match any known suffix"
802    }
803}
804
805# Scan Fortran modules for a given regexp.
806#
807# Argument 0 is the module name
808# Argument 1 is the regexp to match
809proc scan-module { args } {
810    set modfilename [string tolower [lindex $args 0]].mod
811    set fd [open [list | gzip -dc $modfilename] r]
812    set text [read $fd]
813    close $fd
814
815    set testcase [testname-for-summary]
816    if [regexp -- [lindex $args 1] $text] {
817      pass "$testcase scan-module [lindex $args 1]"
818    } else {
819      fail "$testcase scan-module [lindex $args 1]"
820    }
821}
822
823# Scan Fortran modules for absence of a given regexp.
824#
825# Argument 0 is the module name
826# Argument 1 is the regexp to match
827proc scan-module-absence { args } {
828    set modfilename [string tolower [lindex $args 0]].mod
829    set fd [open [list | gzip -dc $modfilename] r]
830    set text [read $fd]
831    close $fd
832
833    set testcase [testname-for-summary]
834    if [regexp -- [lindex $args 1] $text] {
835      fail "$testcase scan-module [lindex $args 1]"
836    } else {
837      pass "$testcase scan-module [lindex $args 1]"
838    }
839}
840
841# Verify that the compiler output file exists, invoked via dg-final.
842proc output-exists { args } {
843    # Process an optional target or xfail list.
844    if { [llength $args] >= 1 } {
845	switch [dg-process-target [lindex $args 0]] {
846	    "S" { }
847	    "N" { return }
848	    "F" { setup_xfail "*-*-*" }
849	    "P" { }
850	}
851    }
852
853    set testcase [testname-for-summary]
854    # Access variable from gcc-dg-test-1.
855    upvar 2 output_file output_file
856
857    if [file exists $output_file] {
858	pass "$testcase output-exists $output_file"
859    } else {
860	fail "$testcase output-exists $output_file"
861    }
862}
863
864# Verify that the compiler output file does not exist, invoked via dg-final.
865proc output-exists-not { args } {
866    # Process an optional target or xfail list.
867    if { [llength $args] >= 1 } {
868	switch [dg-process-target [lindex $args 0]] {
869	    "S" { }
870	    "N" { return }
871	    "F" { setup_xfail "*-*-*" }
872	    "P" { }
873	}
874    }
875
876    set testcase [testname-for-summary]
877    # Access variable from gcc-dg-test-1.
878    upvar 2 output_file output_file
879
880    if [file exists $output_file] {
881	fail "$testcase output-exists-not $output_file"
882    } else {
883	pass "$testcase output-exists-not $output_file"
884    }
885}
886
887# We need to make sure that additional_* are cleared out after every
888# test.  It is not enough to clear them out *before* the next test run
889# because gcc-target-compile gets run directly from some .exp files
890# (outside of any test).  (Those uses should eventually be eliminated.)
891
892# Because the DG framework doesn't provide a hook that is run at the
893# end of a test, we must replace dg-test with a wrapper.
894
895if { [info procs saved-dg-test] == [list] } {
896    rename dg-test saved-dg-test
897
898    # Helper function for cleanups that should happen after the call
899    # to the real dg-test, whether or not it returns normally, or
900    # fails with an error.
901    proc cleanup-after-saved-dg-test { } {
902	global additional_files
903	global additional_sources
904	global additional_sources_used
905	global additional_prunes
906	global compiler_conditional_xfail_data
907	global shouldfail
908	global testname_with_flags
909	global set_target_env_var
910	global set_compiler_env_var
911	global saved_compiler_env_var
912	global keep_saved_temps_suffixes
913	global multiline_expected_outputs
914	global freeform_regexps
915	global save_linenr_varnames
916
917	set additional_files ""
918	set additional_sources ""
919	set additional_sources_used ""
920	set additional_prunes ""
921	set shouldfail 0
922	if [info exists set_target_env_var] {
923	    unset set_target_env_var
924	}
925	if [info exists set_compiler_env_var] {
926	    restore-compiler-env-var
927	    unset set_compiler_env_var
928	    unset saved_compiler_env_var
929	}
930	if [info exists keep_saved_temps_suffixes] {
931	    unset keep_saved_temps_suffixes
932	}
933	unset_timeout_vars
934	if [info exists compiler_conditional_xfail_data] {
935	    unset compiler_conditional_xfail_data
936	}
937	if [info exists testname_with_flags] {
938	    unset testname_with_flags
939	}
940	set multiline_expected_outputs []
941	set freeform_regexps []
942
943	if { [info exists save_linenr_varnames] } {
944	    foreach varname $save_linenr_varnames {
945		# Cleanup varname
946		eval global $varname
947		eval unset $varname
948
949		# Cleanup varname_used, or generate defined-but-not-used
950		# warning.
951		set varname_used used_$varname
952		eval global $varname_used
953		eval set used [info exists $varname_used]
954		if { $used } {
955		    eval unset $varname_used
956		} else {
957		    regsub {^saved_linenr_} $varname "" org_varname
958		    warning "dg-line var $org_varname defined, but not used"
959		}
960	    }
961	    unset save_linenr_varnames
962	}
963    }
964
965    proc dg-test { args } {
966	global errorInfo
967
968	if { [ catch { eval saved-dg-test $args } errmsg ] } {
969	    set saved_info $errorInfo
970	    cleanup-after-saved-dg-test
971	    error $errmsg $saved_info
972	}
973	cleanup-after-saved-dg-test
974    }
975}
976
977if { [info procs saved-dg-warning] == [list] \
978     && [info exists gcc_warning_prefix] } {
979    rename dg-warning saved-dg-warning
980
981    proc dg-warning { args } {
982	# Make this variable available here and to the saved proc.
983	upvar dg-messages dg-messages
984	global gcc_warning_prefix
985
986 	process-message saved-dg-warning "$gcc_warning_prefix" "$args"
987    }
988}
989
990if { [info procs saved-dg-error] == [list] \
991     && [info exists gcc_error_prefix] } {
992    rename dg-error saved-dg-error
993
994    proc dg-error { args } {
995	# Make this variable available here and to the saved proc.
996	upvar dg-messages dg-messages
997	global gcc_error_prefix
998
999	process-message saved-dg-error "$gcc_error_prefix" "$args"
1000    }
1001
1002    # Override dg-bogus at the same time.  It doesn't handle a prefix
1003    # but its expression should include a column number.  Otherwise the
1004    # line number can match the column number for other messages, leading
1005    # to insanity.
1006    rename dg-bogus saved-dg-bogus
1007
1008    proc dg-bogus { args } {
1009	upvar dg-messages dg-messages
1010	process-message saved-dg-bogus "" $args
1011    }
1012}
1013
1014# Set variable VARNAME to LINENR
1015
1016proc dg-line { linenr varname } {
1017    set org_varname $varname
1018    set varname "saved_linenr_$varname"
1019    eval global $varname
1020
1021    # Generate defined-but-previously-defined error.
1022    eval set var_defined [info exists $varname]
1023    if { $var_defined } {
1024	eval set deflinenr \$$varname
1025	error "dg-line var $org_varname defined at line $linenr, but previously defined at line $deflinenr"
1026	return
1027    }
1028
1029    eval set $varname $linenr
1030
1031    # Schedule cleanup of varname by cleanup-after-saved-dg-test
1032    global save_linenr_varnames
1033    if { [info exists save_linenr_varnames] } {
1034	lappend save_linenr_varnames $varname
1035    } else {
1036	set save_linenr_varnames [list $varname]
1037    }
1038}
1039
1040# Modify the regular expression saved by a DejaGnu message directive to
1041# include a prefix and to force the expression to match a single line.
1042# MSGPROC is the procedure to call.
1043# MSGPREFIX is the prefix to prepend.
1044# DGARGS is the original argument list.
1045
1046proc process-message { msgproc msgprefix dgargs } {
1047    upvar dg-messages dg-messages
1048
1049    if { [llength $dgargs] == 5 } {
1050	if { [regsub "^\.\[+-\](\[0-9\]+)$" [lindex $dgargs 4] "\\1" num] } {
1051	    # Handle relative line specification, .+1 or .-1 etc.
1052	    set num [expr [lindex $dgargs 0] [string index [lindex $dgargs 4] 1] $num]
1053	    set dgargs [lreplace $dgargs 4 4 $num]
1054	} elseif { [regsub "^(\[a-zA-Z\]\[a-zA-Z0-9_\]*)$" [lindex $dgargs 4] "\\1" varname] } {
1055	    # Handle linenr variable defined by dg-line
1056
1057	    set org_varname $varname
1058	    set varname "saved_linenr_$varname"
1059	    eval global $varname
1060
1061	    # Generate used-but-not-defined error.
1062	    eval set var_defined [info exists $varname]
1063	    if { ! $var_defined } {
1064		set linenr [expr [lindex $dgargs 0]]
1065		error "dg-line var $org_varname used at line $linenr, but not defined"
1066		return
1067	    }
1068
1069	    # Note that varname has been used.
1070	    set varname_used "used_$varname"
1071	    eval global $varname_used
1072	    eval set $varname_used 1
1073
1074	    # Get line number from var and use it.
1075	    eval set num \$$varname
1076	    set dgargs [lreplace $dgargs 4 4 $num]
1077	}
1078    }
1079
1080    # Process the dg- directive, including adding the regular expression
1081    # to the new message entry in dg-messages.
1082    set msgcnt [llength ${dg-messages}]
1083    eval $msgproc $dgargs
1084
1085    # If the target expression wasn't satisfied there is no new message.
1086    if { [llength ${dg-messages}] == $msgcnt } {
1087	return;
1088    }
1089
1090    # Get the entry for the new message.  Prepend the message prefix to
1091    # the regular expression and make it match a single line.
1092    set newentry [lindex ${dg-messages} end]
1093    set expmsg [lindex $newentry 2]
1094
1095    set column ""
1096    # Handle column numbers from the specified expression (if there is
1097    # one) and set up the search expression that will be used by DejaGnu.
1098    if [regexp {^-:} $expmsg] {
1099	# The expected column is -, so shouldn't appear.
1100	set expmsg [string range $expmsg 2 end]
1101    } elseif [regexp {^[0-9]+:} $expmsg column] {
1102	# The expression in the directive included a column number.
1103	# Remove it from the original expression and move it
1104	# to the proper place in the search expression.
1105	set expmsg [string range $expmsg [string length $column] end]
1106	set column "$column "
1107    } elseif [string match "" [lindex $newentry 0]] {
1108	# The specified line number is 0; don't expect a column number.
1109    } else {
1110	# There is no column number in the search expression, but we
1111	# should expect one in the message itself.
1112	set column {[0-9]+: }
1113    }
1114    set expmsg "$column$msgprefix\[^\n\]*$expmsg"
1115    set newentry [lreplace $newentry 2 2 $expmsg]
1116
1117    set dg-messages [lreplace ${dg-messages} end end $newentry]
1118    verbose "process-message:\n${dg-messages}" 2
1119}
1120
1121# Look for messages that don't have standard prefixes.
1122
1123proc dg-message { args } {
1124    upvar dg-messages dg-messages
1125    process-message saved-dg-warning "" $args
1126}
1127
1128# Look for a location marker of the form
1129#   file:line:column:
1130# with no extra text (e.g. a line-span separator).
1131
1132proc dg-locus { args } {
1133    upvar dg-messages dg-messages
1134
1135    # Process the dg- directive, including adding the regular expression
1136    # to the new message entry in dg-messages.
1137    set msgcnt [llength ${dg-messages}]
1138    eval saved-dg-warning $args
1139
1140    # If the target expression wasn't satisfied there is no new message.
1141    if { [llength ${dg-messages}] == $msgcnt } {
1142	return;
1143    }
1144
1145    # Get the entry for the new message.  Prepend the message prefix to
1146    # the regular expression and make it match a single line.
1147    set newentry [lindex ${dg-messages} end]
1148    set expmsg [lindex $newentry 2]
1149
1150    set newentry [lreplace $newentry 2 2 $expmsg]
1151    set dg-messages [lreplace ${dg-messages} end end $newentry]
1152    verbose "process-message:\n${dg-messages}" 2
1153}
1154
1155# Check the existence of a gdb in the path, and return true if there
1156# is one.
1157#
1158# Set env(GDB_FOR_GCC_TESTING) accordingly.
1159
1160proc gdb-exists { args } {
1161    if ![info exists ::env(GDB_FOR_GCC_TESTING)] {
1162	global GDB
1163	if ![info exists ::env(GDB_FOR_GCC_TESTING)] {
1164	    if [info exists GDB] {
1165		setenv GDB_FOR_GCC_TESTING "$GDB"
1166	    } else {
1167		setenv GDB_FOR_GCC_TESTING "[transform gdb]"
1168	    }
1169	}
1170    }
1171    if { [which $::env(GDB_FOR_GCC_TESTING)] != 0 } {
1172	return 1;
1173    }
1174    return 0;
1175}
1176
1177set additional_prunes ""
1178set dg_runtest_extra_prunes ""
1179