How to detect whether we're inside of a loop??

Kaveh R. Ghazi ghazi@caip.rutgers.edu
Wed Apr 9 22:24:00 GMT 2003


Thanks to all who replied to my original question.  I came up with a
function to do what I wanted.  I've not yet applied it to do anything
useful, so this patch is merely for informational purposes on this
thread for now.  I.e. it's not intended for inclusion in the gcc tree.

The function get_loop_depth() returns how many levels of loop nesting
you're in at the time you call it.  It ignores "do {...} while(0)" loops
to avoid false positives.  (Thanks to Bruce Korb for suggesting that
to me.)

It was tested by calling it from inside an expand_builtin_foo function
in builtins.c and it works correctly used from there.  I don't know if
this code needs a certain state in the compiler to be reached for it
to work, so I can't say if calling it from somewhere else
(i.e. earlier or later in compilation) will still behave correctly.

Comments welcome.

		--Kaveh

PS: now I can play with heuristics which attempt to use it.


2003-04-08  Kaveh R. Ghazi  <ghazi@caip.rutgers.edu>

	* rtl.h (get_loop_depth): Prototype.
	* stmt.c (get_loop_depth): New function.
	
diff -rup orig/egcc-CVS20030407/gcc/rtl.h egcc-CVS20030407/gcc/rtl.h
--- orig/egcc-CVS20030407/gcc/rtl.h	2003-04-06 21:01:05.000000000 -0400
+++ egcc-CVS20030407/gcc/rtl.h	2003-04-08 20:18:47.947896418 -0400
@@ -2084,6 +2084,7 @@ extern void set_file_and_line_for_stmt	P
 extern void expand_null_return		PARAMS ((void));
 extern void emit_jump			PARAMS ((rtx));
 extern int preserve_subexpressions_p	PARAMS ((void));
+extern int get_loop_depth		PARAMS ((void));
 
 /* In expr.c */
 extern void move_by_pieces		PARAMS ((rtx, rtx,
diff -rup orig/egcc-CVS20030407/gcc/stmt.c egcc-CVS20030407/gcc/stmt.c
--- orig/egcc-CVS20030407/gcc/stmt.c	2003-03-24 21:01:13.000000000 -0500
+++ egcc-CVS20030407/gcc/stmt.c	2003-04-08 22:50:16.055405217 -0400
@@ -435,6 +435,25 @@ static void emit_jump_if_reachable	PARAM
 static void emit_case_nodes		PARAMS ((rtx, case_node_ptr, rtx, tree));
 static struct case_node *case_tree2list	PARAMS ((case_node *, case_node *));
 
+/* Determine the number of nested loops at the current location in the
+   source code GCC is compiling.  Ignore "do {...} while(0)" loops.  */
+
+int
+get_loop_depth (void)
+{
+  int depth = 0;
+  struct nesting *ptr = loop_stack;
+
+  while (ptr)
+    {
+      /* Loops whose start_label is a NOTE are "do {...} while(0)".  */
+      if (! NOTE_P (ptr->data.loop.start_label))
+	depth++;
+      ptr = ptr->next;
+    }
+  return depth;
+}
+
 void
 using_eh_for_cleanups ()
 {



More information about the Gcc mailing list