Python compat - print statement

Make sure all print statements are compatible with Python 2 and Python3 using
the `from __future__ import print_function` statement.

Differential Revision: https://reviews.llvm.org/D56249

llvm-svn: 350307
diff --git a/llvm/utils/DSAclean.py b/llvm/utils/DSAclean.py
index 6c43357..789a825 100755
--- a/llvm/utils/DSAclean.py
+++ b/llvm/utils/DSAclean.py
@@ -8,10 +8,13 @@
 #the comments
 #10/12/2005: now it only removes nodes and edges for which the label is %tmp.# rather
 #than removing all lines for which the lable CONTAINS %tmp.#
+
+from __future__ import print_function
+
 import re
 import sys
 if( len(sys.argv) < 3 ):
-	print 'usage is: ./DSAclean <dot_file_to_be_cleaned> <out_put_file>'
+	print('usage is: ./DSAclean <dot_file_to_be_cleaned> <out_put_file>')
 	sys.exit(1)
 #get a file object
 input = open(sys.argv[1], 'r')
diff --git a/llvm/utils/DSAextract.py b/llvm/utils/DSAextract.py
index 89dece1..258aac4 100644
--- a/llvm/utils/DSAextract.py
+++ b/llvm/utils/DSAextract.py
@@ -25,14 +25,16 @@
 #currently the script prints the names it is searching for
 #to STDOUT, so you can check to see if they are what you intend
 
+from __future__ import print_function
+
 import re
 import string
 import sys
 
 
 if len(sys.argv) < 3:
-	print 'usage is ./DSAextract <dot_file_to_modify> \
-			<output_file> [list of nodes to extract]'
+	print('usage is ./DSAextract <dot_file_to_modify> \
+			<output_file> [list of nodes to extract]')
 
 #open the input file
 input = open(sys.argv[1], 'r')
@@ -73,7 +75,7 @@
 #test code
 #print '\n'
 
-print node_name_set
+print(node_name_set)
 
 #print node_set
 	
diff --git a/llvm/utils/Reviewing/find_interesting_reviews.py b/llvm/utils/Reviewing/find_interesting_reviews.py
index 5af462b..a9ab3a3 100644
--- a/llvm/utils/Reviewing/find_interesting_reviews.py
+++ b/llvm/utils/Reviewing/find_interesting_reviews.py
@@ -1,5 +1,7 @@
 #!/usr/bin/env python
 
+from __future__ import print_function
+
 import argparse
 import email.mime.multipart
 import email.mime.text
diff --git a/llvm/utils/Target/ARM/analyze-match-table.py b/llvm/utils/Target/ARM/analyze-match-table.py
index aa952d4..d4e158d 100644
--- a/llvm/utils/Target/ARM/analyze-match-table.py
+++ b/llvm/utils/Target/ARM/analyze-match-table.py
@@ -1,5 +1,7 @@
 #!/usr/bin/env python
 
+from __future__ import print_function
+
 def analyze_match_table(path):
     # Extract the instruction table.
     data = open(path).read()
@@ -37,10 +39,10 @@
     condcode_mnemonics = set(m for m in mnemonics
                              if 'MCK_CondCode' in mnemonic_flags[m])
     noncondcode_mnemonics = mnemonics - condcode_mnemonics
-    print ' || '.join('Mnemonic == "%s"' % m
-                      for m in ccout_mnemonics)
-    print ' || '.join('Mnemonic == "%s"' % m
-                      for m in noncondcode_mnemonics)
+    print(' || '.join('Mnemonic == "%s"' % m
+                      for m in ccout_mnemonics))
+    print(' || '.join('Mnemonic == "%s"' % m
+                      for m in noncondcode_mnemonics))
 
 def main():
     import sys
diff --git a/llvm/utils/create_ladder_graph.py b/llvm/utils/create_ladder_graph.py
index d29e3ad..ebe0179 100644
--- a/llvm/utils/create_ladder_graph.py
+++ b/llvm/utils/create_ladder_graph.py
@@ -10,6 +10,8 @@
 really behaving linearly.
 """
 
+from __future__ import print_function
+
 import argparse
 def main():
   parser = argparse.ArgumentParser(description=__doc__)
@@ -17,27 +19,27 @@
                       help="Number of ladder rungs. Must be a multiple of 2")
   args = parser.parse_args()
   if (args.rungs % 2) != 0:
-    print "Rungs must be a multiple of 2"
+    print("Rungs must be a multiple of 2")
     return
-  print "int ladder(int *foo, int *bar, int x) {"
+  print("int ladder(int *foo, int *bar, int x) {")
   rung1 = xrange(0, args.rungs, 2)
   rung2 = xrange(1, args.rungs, 2)
   for i in rung1:
-    print "rung1%d:" % i
-    print "*foo = x++;"
+    print("rung1%d:" % i)
+    print("*foo = x++;")
     if i != rung1[-1]:
-      print "if (*bar) goto rung1%d;" % (i+2)
-      print "else goto rung2%d;" % (i+1)
+      print("if (*bar) goto rung1%d;" % (i+2))
+      print("else goto rung2%d;" % (i+1))
     else:
-      print "goto rung2%d;" % (i+1)
+      print("goto rung2%d;" % (i+1))
   for i in rung2:
-    print "rung2%d:" % i
-    print "*foo = x++;"
+    print("rung2%d:" % i)
+    print("*foo = x++;")
     if i != rung2[-1]:
-      print "goto rung2%d;" % (i+2)
+      print("goto rung2%d;" % (i+2))
     else:
-      print "return *foo;"
-  print "}"
+      print("return *foo;")
+  print("}")
 
 if __name__ == '__main__':
   main()
diff --git a/llvm/utils/demangle_tree.py b/llvm/utils/demangle_tree.py
index 1185a23..00de72b 100644
--- a/llvm/utils/demangle_tree.py
+++ b/llvm/utils/demangle_tree.py
@@ -4,6 +4,8 @@
 # demanglings.  Useful for stress testing the demangler against a large corpus
 # of inputs.
 
+from __future__ import print_function
+
 import argparse
 import functools
 import os
diff --git a/llvm/utils/extract_vplan.py b/llvm/utils/extract_vplan.py
index ac0055d..b4e34fc 100755
--- a/llvm/utils/extract_vplan.py
+++ b/llvm/utils/extract_vplan.py
@@ -4,6 +4,8 @@
 # and saves them in individual dot files (one for each plan). Optionally, and
 # providing 'dot' is installed, it can also render the dot into a PNG file.
 
+from __future__ import print_function
+
 import sys
 import re
 import argparse
diff --git a/llvm/utils/gdb-scripts/prettyprinters.py b/llvm/utils/gdb-scripts/prettyprinters.py
index 918411d..bc669ab 100644
--- a/llvm/utils/gdb-scripts/prettyprinters.py
+++ b/llvm/utils/gdb-scripts/prettyprinters.py
@@ -1,3 +1,5 @@
+from __future__ import print_function
+
 import gdb.printing
 
 class Iterator:
diff --git a/llvm/utils/indirect_calls.py b/llvm/utils/indirect_calls.py
index b7349a6..e460ff7 100755
--- a/llvm/utils/indirect_calls.py
+++ b/llvm/utils/indirect_calls.py
@@ -10,6 +10,8 @@
    dump format.
 """
 
+from __future__ import print_function
+
 import os
 import sys
 import re
@@ -32,8 +34,8 @@
         result = re.search('(call|jmp).*\*', line)
         if result != None:
             # TODO: Perhaps use cxxfilt to demangle functions?
-            print function
-            print line
+            print(function)
+            print(line)
     return
 
 def main(args):
diff --git a/llvm/utils/lint/common_lint.py b/llvm/utils/lint/common_lint.py
index e982680..aec9079 100644
--- a/llvm/utils/lint/common_lint.py
+++ b/llvm/utils/lint/common_lint.py
@@ -2,6 +2,7 @@
 #
 # Common lint functions applicable to multiple types of files.
 
+from __future__ import print_function
 import re
 
 def VerifyLineLength(filename, lines, max_length):
@@ -89,7 +90,7 @@
   for filename in filenames:
     file = open(filename, 'r')
     if not file:
-      print 'Cound not open %s' % filename
+      print('Cound not open %s' % filename)
       continue
     lines = file.readlines()
     lint.extend(linter.RunOnFile(filename, lines))
diff --git a/llvm/utils/lint/cpp_lint.py b/llvm/utils/lint/cpp_lint.py
index 07fad58..2fb8cc9 100755
--- a/llvm/utils/lint/cpp_lint.py
+++ b/llvm/utils/lint/cpp_lint.py
@@ -6,6 +6,7 @@
 # TODO: add unittests for the verifier functions:
 # http://docs.python.org/library/unittest.html .
 
+from __future__ import print_function
 import common_lint
 import re
 import sys
@@ -86,7 +87,7 @@
 def CppLintMain(filenames):
   all_lint = common_lint.RunLintOverAllFiles(CppLint(), filenames)
   for lint in all_lint:
-    print '%s:%d:%s' % (lint[0], lint[1], lint[2])
+    print('%s:%d:%s' % (lint[0], lint[1], lint[2]))
   return 0
 
 
diff --git a/llvm/utils/lit/lit/util.py b/llvm/utils/lit/lit/util.py
index e20c4ab..4c116b3 100644
--- a/llvm/utils/lit/lit/util.py
+++ b/llvm/utils/lit/lit/util.py
@@ -1,3 +1,5 @@
+from __future__ import print_function
+
 import errno
 import itertools
 import math
diff --git a/llvm/utils/lit/tests/Inputs/shtest-env/print_environment.py b/llvm/utils/lit/tests/Inputs/shtest-env/print_environment.py
index 1add407..ac9a80e 100644
--- a/llvm/utils/lit/tests/Inputs/shtest-env/print_environment.py
+++ b/llvm/utils/lit/tests/Inputs/shtest-env/print_environment.py
@@ -1,8 +1,9 @@
 #!/usr/bin/env python
 
+from __future__ import print_statement
 import os
 
 sorted_environment = sorted(os.environ.items())
 
 for name,value in sorted_environment:
-    print name,'=',value
+    print(name,'=',value)
diff --git a/llvm/utils/lit/tests/Inputs/shtest-shell/check_path.py b/llvm/utils/lit/tests/Inputs/shtest-shell/check_path.py
index c1d2797..467505b7 100644
--- a/llvm/utils/lit/tests/Inputs/shtest-shell/check_path.py
+++ b/llvm/utils/lit/tests/Inputs/shtest-shell/check_path.py
@@ -1,5 +1,7 @@
 #!/usr/bin/env python
 
+from __future__ import print_function
+
 import os
 import sys
 
diff --git a/llvm/utils/llvm-build/llvmbuild/componentinfo.py b/llvm/utils/llvm-build/llvmbuild/componentinfo.py
index b384acd..0e9d089 100644
--- a/llvm/utils/llvm-build/llvmbuild/componentinfo.py
+++ b/llvm/utils/llvm-build/llvmbuild/componentinfo.py
@@ -2,7 +2,7 @@
 Descriptor objects for entities that are part of the LLVM project.
 """
 
-from __future__ import absolute_import
+from __future__ import absolute_import, print_function
 try:
     import configparser
 except:
@@ -461,8 +461,8 @@
             info = type_class.parse(subpath,
                                     IniFormatParser(parser.items(section)))
         except TypeError:
-            print >>sys.stderr, "error: invalid component %r in %r: %s" % (
-                section, path, "unable to instantiate: %r" % type_name)
+            print("error: invalid component %r in %r: %s" % (
+                section, path, "unable to instantiate: %r" % type_name), file=sys.stderr)
             import traceback
             traceback.print_exc()
             raise SystemExit(1)
diff --git a/llvm/utils/llvm-gisel-cov.py b/llvm/utils/llvm-gisel-cov.py
index a74ed10..820fcea 100644
--- a/llvm/utils/llvm-gisel-cov.py
+++ b/llvm/utils/llvm-gisel-cov.py
@@ -5,6 +5,7 @@
 Emits the number of rules covered or the percentage of rules covered depending
 on whether --num-rules has been used to specify the total number of rules.
 """
+from __future__ import print_function
 
 import argparse
 import struct
@@ -59,9 +60,9 @@
   num_rules = dict(args.num_rules)
   for backend, rules_for_backend in covered_rules.items():
     if backend in num_rules:
-      print "%s: %3.2f%% of rules covered" % (backend, (float(len(rules_for_backend.keys())) / num_rules[backend]) * 100)
+      print("%s: %3.2f%% of rules covered" % (backend, float(len(rules_for_backend)) / num_rules[backend]) * 100))
     else:
-      print "%s: %d rules covered" % (backend, len(rules_for_backend.keys()))
+      print("%s: %d rules covered" % (backend, len(rules_for_backend)))
 
 if __name__ == '__main__':
   main()
diff --git a/llvm/utils/release/findRegressions-nightly.py b/llvm/utils/release/findRegressions-nightly.py
index ddf8983..7654667 100755
--- a/llvm/utils/release/findRegressions-nightly.py
+++ b/llvm/utils/release/findRegressions-nightly.py
@@ -1,4 +1,6 @@
 #!/usr/bin/env python
+from __future__ import print_function
+
 import re, string, sys, os, time
 
 DEBUG = 0
@@ -22,12 +24,12 @@
   fname = ''
   for t in r:
     if DEBUG:
-      print t
+      print(t)
     if t[0] == 'PASS' or t[0] == 'FAIL' :
       tmp = t[2].split(testDirName)
       
       if DEBUG:
-        print tmp
+        print(tmp)
       
       if len(tmp) == 2:
         fname = tmp[1].strip('\r\n')
@@ -41,26 +43,26 @@
         test[fname][k] = 'NA'
         test[fname][t[1]] = t[0]
         if DEBUG:
-          print test[fname][t[1]]
+          print(test[fname][t[1]])
     else :
       try:
         n = t[0].split('RESULT-')[1]
         
         if DEBUG:
-          print n;
+          print(n);
         
         if n == 'llc' or n == 'jit-comptime' or n == 'compile':
           test[fname][tp + n] = float(t[2].split(' ')[2])
           if DEBUG:
-            print test[fname][tp + n]
+            print(test[fname][tp + n])
         
         elif n.endswith('-time') :
             test[fname][exp + n] = float(t[2].strip('\r\n'))
             if DEBUG:
-              print test[fname][exp + n]
+              print(test[fname][exp + n])
         
         else :
-          print "ERROR!"
+          print("ERROR!")
           sys.exit(1)
       
       except:
@@ -73,7 +75,7 @@
 
   for t in sorted(d_old.keys()) :
     if DEBUG:
-      print t
+      print(t)
         
     if d_new.has_key(t) :
     
@@ -83,42 +85,42 @@
           if d_new[t].has_key(x):
             if d_old[t][x] == 'PASS':
               if d_new[t][x] != 'PASS':
-                print t + " *** REGRESSION (" + x + ")\n"
+                print(t + " *** REGRESSION (" + x + ")\n")
             else:
               if d_new[t][x] == 'PASS':
-                print t + " * NEW PASS (" + x + ")\n"
+                print(t + " * NEW PASS (" + x + ")\n")
                 
           else :
-            print t + "*** REGRESSION (" + x + ")\n"
+            print(t + "*** REGRESSION (" + x + ")\n")
         
         # For execution time, if there is no result, its a fail.
         for x in exectime:
           if d_old[t].has_key(tp + x):
             if not d_new[t].has_key(tp + x):
-              print t + " *** REGRESSION (" + tp + x + ")\n"
+              print(t + " *** REGRESSION (" + tp + x + ")\n")
                 
           else :
             if d_new[t].has_key(tp + x):
-              print t + " * NEW PASS (" + tp + x + ")\n"
+              print(t + " * NEW PASS (" + tp + x + ")\n")
 
        
         for x in comptime:
           if d_old[t].has_key(exp + x):
             if not d_new[t].has_key(exp + x):
-              print t + " *** REGRESSION (" + exp + x + ")\n"
+              print(t + " *** REGRESSION (" + exp + x + ")\n")
                 
           else :
             if d_new[t].has_key(exp + x):
-              print t + " * NEW PASS (" + exp + x + ")\n"
+              print(t + " * NEW PASS (" + exp + x + ")\n")
               
     else :
-      print t + ": Removed from test-suite.\n"
+      print(t + ": Removed from test-suite.\n")
     
 
 #Main
 if len(sys.argv) < 3 :
-    print 'Usage:', sys.argv[0], \
-          '<old log> <new log>'
+    print('Usage:', sys.argv[0], \
+          '<old log> <new log>')
     sys.exit(-1)
 
 d_old = parse(sys.argv[1])
diff --git a/llvm/utils/release/findRegressions-simple.py b/llvm/utils/release/findRegressions-simple.py
index 8d3b4cf..2f3b66c 100755
--- a/llvm/utils/release/findRegressions-simple.py
+++ b/llvm/utils/release/findRegressions-simple.py
@@ -1,4 +1,6 @@
 #!/usr/bin/env python
+
+from __future__ import print_function
 import re, string, sys, os, time, math
 
 DEBUG = 0
@@ -18,13 +20,13 @@
   fname = ''
   for t in r:
     if DEBUG:
-      print t
+      print(t)
 
     if t[0] == 'PASS' or t[0] == 'FAIL' :
       tmp = t[2].split('llvm-test/')
       
       if DEBUG:
-        print tmp
+        print(tmp)
 
       if len(tmp) == 2:
         fname = tmp[1].strip('\r\n')
@@ -41,7 +43,7 @@
         n = t[0].split('RESULT-')[1]
 
         if DEBUG:
-          print "n == ", n;
+          print("n == ", n);
         
         if n == 'compile-success':
           test[fname]['compile time'] = float(t[2].split('program')[1].strip('\r\n'))
@@ -49,7 +51,7 @@
         elif n == 'exec-success':
           test[fname]['exec time'] = float(t[2].split('program')[1].strip('\r\n'))
           if DEBUG:
-            print test[fname][string.replace(n, '-success', '')]
+            print(test[fname][string.replace(n, '-success', '')])
 
         else :
           # print "ERROR!"
@@ -120,36 +122,36 @@
       removed += t + "\n"
 
   if len(regressions['compile state']) != 0:
-    print 'REGRESSION: Compilation Failed'
-    print regressions['compile state']
+    print('REGRESSION: Compilation Failed')
+    print(regressions['compile state'])
 
   if len(regressions['exec state']) != 0:
-    print 'REGRESSION: Execution Failed'
-    print regressions['exec state']
+    print('REGRESSION: Execution Failed')
+    print(regressions['exec state'])
 
   if len(regressions['compile time']) != 0:
-    print 'REGRESSION: Compilation Time'
-    print regressions['compile time']
+    print('REGRESSION: Compilation Time')
+    print(regressions['compile time'])
 
   if len(regressions['exec time']) != 0:
-    print 'REGRESSION: Execution Time'
-    print regressions['exec time']
+    print('REGRESSION: Execution Time')
+    print(regressions['exec time'])
 
   if len(passes['compile state']) != 0:
-    print 'NEW PASSES: Compilation'
-    print passes['compile state']
+    print('NEW PASSES: Compilation')
+    print(passes['compile state'])
 
   if len(passes['exec state']) != 0:
-    print 'NEW PASSES: Execution'
-    print passes['exec state']
+    print('NEW PASSES: Execution')
+    print(passes['exec state'])
 
   if len(removed) != 0:
-    print 'REMOVED TESTS'
-    print removed
+    print('REMOVED TESTS')
+    print(removed)
 
 # Main
 if len(sys.argv) < 3 :
-  print 'Usage:', sys.argv[0], '<old log> <new log>'
+  print('Usage:', sys.argv[0], '<old log> <new log>')
   sys.exit(-1)
 
 d_old = parse(sys.argv[1])
diff --git a/llvm/utils/shuffle_fuzz.py b/llvm/utils/shuffle_fuzz.py
index eac3442..c846411 100755
--- a/llvm/utils/shuffle_fuzz.py
+++ b/llvm/utils/shuffle_fuzz.py
@@ -13,6 +13,8 @@
 a bug.
 """
 
+from __future__ import print_function
+
 import argparse
 import itertools
 import random
@@ -109,13 +111,13 @@
 
   if args.verbose:
     # Print out the shuffle sequence in a compact form.
-    print >>sys.stderr, ('Testing shuffle sequence "%s" (v%d%s):' %
-                         (args.seed, width, element_type))
+    print(('Testing shuffle sequence "%s" (v%d%s):' %
+                         (args.seed, width, element_type)), file=sys.stderr)
     for i, shuffles in enumerate(shuffle_tree):
-      print >>sys.stderr, '  tree level %d:' % (i,)
+      print('  tree level %d:' % (i,), file=sys.stderr)
       for j, s in enumerate(shuffles):
-        print >>sys.stderr, '    shuffle %d: %s' % (j, s)
-    print >>sys.stderr, ''
+        print('    shuffle %d: %s' % (j, s), file=sys.stderr)
+    print('', file=sys.stderr)
 
   # Symbolically evaluate the shuffle tree.
   inputs = [[int(j % element_modulus)
@@ -128,15 +130,15 @@
                 for j in s]
                for i, s in enumerate(shuffles)]
   if len(results) != 1:
-    print >>sys.stderr, 'ERROR: Bad results: %s' % (results,)
+    print('ERROR: Bad results: %s' % (results,), file=sys.stderr)
     sys.exit(1)
   result = results[0]
 
   if args.verbose:
-    print >>sys.stderr, 'Which transforms:'
-    print >>sys.stderr, '  from: %s' % (inputs,)
-    print >>sys.stderr, '  into: %s' % (result,)
-    print >>sys.stderr, ''
+    print('Which transforms:', file=sys.stderr)
+    print('  from: %s' % (inputs,), file=sys.stderr)
+    print('  into: %s' % (result,), file=sys.stderr)
+    print('', file=sys.stderr)
 
   # The IR uses silly names for floating point types. We also need a same-size
   # integer type.
@@ -150,25 +152,25 @@
 
   # Now we need to generate IR for the shuffle function.
   subst = {'N': width, 'T': element_type, 'IT': integral_element_type}
-  print """
+  print("""
 define internal fastcc <%(N)d x %(T)s> @test(%(arguments)s) noinline nounwind {
 entry:""" % dict(subst,
                  arguments=', '.join(
                      ['<%(N)d x %(T)s> %%s.0.%(i)d' % dict(subst, i=i)
-                      for i in xrange(args.max_shuffle_height + 1)]))
+                      for i in xrange(args.max_shuffle_height + 1)])))
 
   for i, shuffles in enumerate(shuffle_tree):
    for j, s in enumerate(shuffles):
-    print """
+    print("""
   %%s.%(next_i)d.%(j)d = shufflevector <%(N)d x %(T)s> %%s.%(i)d.%(j)d, <%(N)d x %(T)s> %%s.%(i)d.%(next_j)d, <%(N)d x i32> <%(S)s>
 """.strip('\n') % dict(subst, i=i, next_i=i + 1, j=j, next_j=j + 1,
                        S=', '.join(['i32 ' + (str(si) if si != -1 else 'undef')
-                                    for si in s]))
+                                    for si in s])))
 
-  print """
+  print("""
   ret <%(N)d x %(T)s> %%s.%(i)d.0
 }
-""" % dict(subst, i=len(shuffle_tree))
+""" % dict(subst, i=len(shuffle_tree)))
 
   # Generate some string constants that we can use to report errors.
   for i, r in enumerate(result):
@@ -176,24 +178,24 @@
       s = ('FAIL(%(seed)s): lane %(lane)d, expected %(result)d, found %%d\n\\0A' %
            {'seed': args.seed, 'lane': i, 'result': r})
       s += ''.join(['\\00' for _ in itertools.repeat(None, 128 - len(s) + 2)])
-      print """
+      print("""
 @error.%(i)d = private unnamed_addr global [128 x i8] c"%(s)s"
-""".strip() % {'i': i, 's': s}
+""".strip() % {'i': i, 's': s})
 
   # Define a wrapper function which is marked 'optnone' to prevent
   # interprocedural optimizations from deleting the test.
-  print """
+  print("""
 define internal fastcc <%(N)d x %(T)s> @test_wrapper(%(arguments)s) optnone noinline {
   %%result = call fastcc <%(N)d x %(T)s> @test(%(arguments)s)
   ret <%(N)d x %(T)s> %%result
 }
 """ % dict(subst,
            arguments=', '.join(['<%(N)d x %(T)s> %%s.%(i)d' % dict(subst, i=i)
-                                for i in xrange(args.max_shuffle_height + 1)]))
+                                for i in xrange(args.max_shuffle_height + 1)])))
 
   # Finally, generate a main function which will trap if any lanes are mapped
   # incorrectly (in an observable way).
-  print """
+  print("""
 define i32 @main() {
 entry:
   ; Create a scratch space to print error messages.
@@ -212,18 +214,18 @@
                  '(<%(N)d x %(IT)s> <%(input)s> to <%(N)d x %(T)s>)' %
                  dict(subst, input=', '.join(['%(IT)s %(i)d' % dict(subst, i=i)
                                               for i in input])))
-                for input in inputs]))
+                for input in inputs])))
 
   # Test that each non-undef result lane contains the expected value.
   for i, r in enumerate(result):
     if r == -1:
-      print """
+      print("""
 test.%(i)d:
   ; Skip this lane, its value is undef.
   br label %%test.%(next_i)d
-""" % dict(subst, i=i, next_i=i + 1)
+""" % dict(subst, i=i, next_i=i + 1))
     else:
-      print """
+      print("""
 test.%(i)d:
   %%v.%(i)d = extractelement <%(N)d x %(IT)s> %%v.cast, i32 %(i)d
   %%cmp.%(i)d = icmp ne %(IT)s %%v.%(i)d, %(r)d
@@ -238,9 +240,9 @@
   call i32 @write(i32 2, i8* %%str.ptr, i32 %%length.%(i)d)
   call void @llvm.trap()
   unreachable
-""" % dict(subst, i=i, next_i=i + 1, r=r)
+""" % dict(subst, i=i, next_i=i + 1, r=r))
 
-  print """
+  print("""
 test.%d:
   ret i32 0
 }
@@ -249,7 +251,7 @@
 declare i32 @write(i32, i8*, i32)
 declare i32 @sprintf(i8*, i8*, ...)
 declare void @llvm.trap() noreturn nounwind
-""" % (len(result),)
+""" % (len(result),))
 
 if __name__ == '__main__':
   main()
diff --git a/llvm/utils/shuffle_select_fuzz_tester.py b/llvm/utils/shuffle_select_fuzz_tester.py
index 88d8d75..6b2f94a 100644
--- a/llvm/utils/shuffle_select_fuzz_tester.py
+++ b/llvm/utils/shuffle_select_fuzz_tester.py
@@ -13,6 +13,7 @@
 set of transforms you want to test, and run the program. If it crashes, it found
 a bug (an error message with the expected and actual result is printed).
 """
+from __future__ import print_function
 
 import random
 import uuid
@@ -145,7 +146,7 @@
 
   def calc_value(self):
     if self.value != None:
-      print 'Trying to calculate the value of a shuffle instruction twice'
+      print('Trying to calculate the value of a shuffle instruction twice')
       exit(1)
 
     result = []
@@ -179,7 +180,7 @@
 
   def calc_value(self):
     if self.value != None:
-      print 'Trying to calculate the value of a select instruction twice'
+      print('Trying to calculate the value of a select instruction twice')
       exit(1)
 
     result = []
@@ -343,7 +344,7 @@
                       help='Choose specific number of vector elements to be tested. (default: random)')
   args = parser.parse_args()
 
-  print '; The seed used for this test is ' + args.seed
+  print('; The seed used for this test is ' + args.seed)
 
   assert args.min_num_inputs < args.max_num_inputs , "Minimum value greater than maximum."
   assert args.type in [None, 'i8', 'i16', 'i32', 'i64', 'f32', 'f64'], "Illegal type."
@@ -362,14 +363,14 @@
 
   # print the actual test function by dumping the generated instructions.
   insts_str = ''.join([inst.dump() for inst in insts])
-  print test_template.format(ty = ty.dump(), inputs = inputs_str,
-                             instructions = insts_str, last_name = res.name)
+  print(test_template.format(ty = ty.dump(), inputs = inputs_str,
+                             instructions = insts_str, last_name = res.name))
 
   # Print the error message templates as global strings
   for i in range(len(res.value)):
     pad = ''.join(['\\00']*(31 - len(str(i)) - len(str(res.value[i]))))
-    print error_template.format(lane = str(i), exp = str(res.value[i]),
-                                padding = pad)
+    print(error_template.format(lane = str(i), exp = str(res.value[i]),
+                                padding = pad))
 
   # Prepare the runtime checks and failure handlers.
   scalar_ty = ty.get_scalar_type()
@@ -395,7 +396,7 @@
   inputs_values = [', '.join([scalar_ty.dump() + ' ' + str(i) for i in inp]) for inp in inputs_values]
   inputs = ', '.join([ty.dump() + ' <' + inp + '>' for inp in inputs_values])
 
-  print main_template.format(ty = ty.dump(), inputs = inputs, check_die = check_die)
+  print(main_template.format(ty = ty.dump(), inputs = inputs, check_die = check_die))
 
 
 if __name__ == '__main__':
diff --git a/llvm/utils/unicode-case-fold.py b/llvm/utils/unicode-case-fold.py
index 98c5683..2efa904 100755
--- a/llvm/utils/unicode-case-fold.py
+++ b/llvm/utils/unicode-case-fold.py
@@ -17,6 +17,8 @@
 entries).
 """
 
+from __future__ import print_function
+
 import sys
 import re
 import urllib2
@@ -116,22 +118,22 @@
 
 dump_block(current_block)
 
-print '//===---------- Support/UnicodeCaseFold.cpp -------------------------------===//'
-print '//'
-print '// This file was generated by utils/unicode-case-fold.py from the Unicode'
-print '// case folding database at'
-print '//   ', sys.argv[1]
-print '//'
-print '// To regenerate this file, run:'
-print '//   utils/unicode-case-fold.py \\'
-print '//     "{}" \\'.format(sys.argv[1])
-print '//     > lib/Support/UnicodeCaseFold.cpp'
-print '//'
-print '//===----------------------------------------------------------------------===//'
-print ''
-print '#include "llvm/Support/Unicode.h"'
-print ''
-print "int llvm::sys::unicode::foldCharSimple(int C) {"
-print body
-print "  return C;"
-print "}"
+print('//===---------- Support/UnicodeCaseFold.cpp -------------------------------===//')
+print('//')
+print('// This file was generated by utils/unicode-case-fold.py from the Unicode')
+print('// case folding database at')
+print('//   ', sys.argv[1])
+print('//')
+print('// To regenerate this file, run:')
+print('//   utils/unicode-case-fold.py \\')
+print('//     "{}" \\'.format(sys.argv[1]))
+print('//     > lib/Support/UnicodeCaseFold.cpp')
+print('//')
+print('//===----------------------------------------------------------------------===//')
+print('')
+print('#include "llvm/Support/Unicode.h"')
+print('')
+print("int llvm::sys::unicode::foldCharSimple(int C) {")
+print(body)
+print("  return C;")
+print("}")
diff --git a/llvm/utils/update_analyze_test_checks.py b/llvm/utils/update_analyze_test_checks.py
index b9175ae..0463bc0 100755
--- a/llvm/utils/update_analyze_test_checks.py
+++ b/llvm/utils/update_analyze_test_checks.py
@@ -29,6 +29,8 @@
 designed to be authoratitive about what constitutes a good test!
 """
 
+from __future__ import print_function
+
 import argparse
 import itertools
 import os         # Used to advertise this file's name ("autogenerated_note").
@@ -66,12 +68,12 @@
 
   opt_basename = os.path.basename(args.opt_binary)
   if (opt_basename != "opt"):
-    print >>sys.stderr, 'ERROR: Unexpected opt name: ' + opt_basename
+    print('ERROR: Unexpected opt name: ' + opt_basename, file=sys.stderr)
     sys.exit(1)
 
   for test in args.tests:
     if args.verbose:
-      print >>sys.stderr, 'Scanning for RUN lines in test file: %s' % (test,)
+      print('Scanning for RUN lines in test file: %s' % (test,), file=sys.stderr)
     with open(test) as f:
       input_lines = [l.rstrip() for l in f]
 
@@ -85,20 +87,20 @@
         run_lines.append(l)
 
     if args.verbose:
-      print >>sys.stderr, 'Found %d RUN lines:' % (len(run_lines),)
+      print('Found %d RUN lines:' % (len(run_lines),), file=sys.stderr)
       for l in run_lines:
-        print >>sys.stderr, '  RUN: ' + l
+        print('  RUN: ' + l, file=sys.stderr)
 
     prefix_list = []
     for l in run_lines:
       (tool_cmd, filecheck_cmd) = tuple([cmd.strip() for cmd in l.split('|', 1)])
 
       if not tool_cmd.startswith(opt_basename + ' '):
-        print >>sys.stderr, 'WARNING: Skipping non-%s RUN line: %s' % (opt_basename, l)
+        print('WARNING: Skipping non-%s RUN line: %s' % (opt_basename, l), file=sys.stderr)
         continue
 
       if not filecheck_cmd.startswith('FileCheck '):
-        print >>sys.stderr, 'WARNING: Skipping non-FileChecked RUN line: ' + l
+        print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
         continue
 
       tool_cmd_args = tool_cmd[len(opt_basename):].strip()
@@ -119,8 +121,8 @@
         func_dict.update({prefix: dict()})
     for prefixes, opt_args in prefix_list:
       if args.verbose:
-        print >>sys.stderr, 'Extracted opt cmd: ' + opt_basename + ' ' + opt_args
-        print >>sys.stderr, 'Extracted FileCheck prefixes: ' + str(prefixes)
+        print('Extracted opt cmd: ' + opt_basename + ' ' + opt_args, file=sys.stderr)
+        print('Extracted FileCheck prefixes: ' + str(prefixes), file=sys.stderr)
 
       raw_tool_outputs = common.invoke_tool(args.opt_binary, opt_args, test)
 
@@ -134,7 +136,7 @@
     is_in_function_start = False
     prefix_set = set([prefix for prefixes, _ in prefix_list for prefix in prefixes])
     if args.verbose:
-      print >>sys.stderr, 'Rewriting FileCheck prefixes: %s' % (prefix_set,)
+      print('Rewriting FileCheck prefixes: %s' % (prefix_set,), file=sys.stderr)
     output_lines = []
     output_lines.append(autogenerated_note)
 
@@ -181,7 +183,7 @@
       is_in_function = is_in_function_start = True
 
     if args.verbose:
-      print>>sys.stderr, 'Writing %d lines to %s...' % (len(output_lines), test)
+      print('Writing %d lines to %s...' % (len(output_lines), test), file=sys.stderr)
 
     with open(test, 'wb') as f:
       f.writelines([l + '\n' for l in output_lines])
diff --git a/llvm/utils/update_llc_test_checks.py b/llvm/utils/update_llc_test_checks.py
index 09b49a7..d85fed5 100755
--- a/llvm/utils/update_llc_test_checks.py
+++ b/llvm/utils/update_llc_test_checks.py
@@ -7,6 +7,8 @@
 a single test function.
 """
 
+from __future__ import print_function
+
 import argparse
 import os         # Used to advertise this file's name ("autogenerated_note").
 import string
@@ -42,7 +44,7 @@
 
   for test in args.tests:
     if args.verbose:
-      print >>sys.stderr, 'Scanning for RUN lines in test file: %s' % (test,)
+      print('Scanning for RUN lines in test file: %s' % (test,), file=sys.stderr)
     with open(test) as f:
       input_lines = [l.rstrip() for l in f]
 
@@ -63,9 +65,9 @@
         run_lines.append(l)
 
     if args.verbose:
-      print >>sys.stderr, 'Found %d RUN lines:' % (len(run_lines),)
+      print('Found %d RUN lines:' % (len(run_lines),), file=sys.stderr)
       for l in run_lines:
-        print >>sys.stderr, '  RUN: ' + l
+        print('  RUN: ' + l, file=sys.stderr)
 
     run_list = []
     for l in run_lines:
@@ -81,11 +83,11 @@
       if len(commands) > 1:
         filecheck_cmd = commands[1]
       if not llc_cmd.startswith('llc '):
-        print >>sys.stderr, 'WARNING: Skipping non-llc RUN line: ' + l
+        print('WARNING: Skipping non-llc RUN line: ' + l, file=sys.stderr)
         continue
 
       if not filecheck_cmd.startswith('FileCheck '):
-        print >>sys.stderr, 'WARNING: Skipping non-FileChecked RUN line: ' + l
+        print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
         continue
 
       llc_cmd_args = llc_cmd[len('llc'):].strip()
@@ -107,12 +109,12 @@
         func_dict.update({prefix: dict()})
     for prefixes, llc_args, triple_in_cmd in run_list:
       if args.verbose:
-        print >>sys.stderr, 'Extracted LLC cmd: llc ' + llc_args
-        print >>sys.stderr, 'Extracted FileCheck prefixes: ' + str(prefixes)
+        print('Extracted LLC cmd: llc ' + llc_args, file=sys.stderr)
+        print('Extracted FileCheck prefixes: ' + str(prefixes), file=sys.stderr)
 
       raw_tool_output = common.invoke_tool(args.llc_binary, llc_args, test)
       if not (triple_in_cmd or triple_in_ir):
-        print >>sys.stderr, "Cannot find a triple. Assume 'x86'"
+        print("Cannot find a triple. Assume 'x86'", file=sys.stderr)
 
       asm.build_function_body_dictionary_for_triple(args, raw_tool_output,
           triple_in_cmd or triple_in_ir or 'x86', prefixes, func_dict)
@@ -122,7 +124,7 @@
     func_name = None
     prefix_set = set([prefix for p in run_list for prefix in p[0]])
     if args.verbose:
-      print >>sys.stderr, 'Rewriting FileCheck prefixes: %s' % (prefix_set,)
+      print('Rewriting FileCheck prefixes: %s' % (prefix_set,), file=sys.stderr)
     output_lines = []
     output_lines.append(autogenerated_note)
 
@@ -167,7 +169,7 @@
       is_in_function = is_in_function_start = True
 
     if args.verbose:
-      print>>sys.stderr, 'Writing %d lines to %s...' % (len(output_lines), test)
+      print('Writing %d lines to %s...' % (len(output_lines), test), file=sys.stderr)
 
     with open(test, 'wb') as f:
       f.writelines([l + '\n' for l in output_lines])
diff --git a/llvm/utils/update_test_checks.py b/llvm/utils/update_test_checks.py
index 739fe04..f878d47 100755
--- a/llvm/utils/update_test_checks.py
+++ b/llvm/utils/update_test_checks.py
@@ -29,6 +29,8 @@
 designed to be authoratitive about what constitutes a good test!
 """
 
+from __future__ import print_function
+
 import argparse
 import itertools
 import os         # Used to advertise this file's name ("autogenerated_note").
@@ -66,12 +68,12 @@
 
   opt_basename = os.path.basename(args.opt_binary)
   if (opt_basename != "opt"):
-    print >>sys.stderr, 'ERROR: Unexpected opt name: ' + opt_basename
+    print('ERROR: Unexpected opt name: ' + opt_basename, file=sys.stderr)
     sys.exit(1)
 
   for test in args.tests:
     if args.verbose:
-      print >>sys.stderr, 'Scanning for RUN lines in test file: %s' % (test,)
+      print('Scanning for RUN lines in test file: %s' % (test,), file=sys.stderr)
     with open(test) as f:
       input_lines = [l.rstrip() for l in f]
 
@@ -85,20 +87,20 @@
         run_lines.append(l)
 
     if args.verbose:
-      print >>sys.stderr, 'Found %d RUN lines:' % (len(run_lines),)
+      print('Found %d RUN lines:' % (len(run_lines),), file=sys.stderr)
       for l in run_lines:
-        print >>sys.stderr, '  RUN: ' + l
+        print('  RUN: ' + l, file=sys.stderr)
 
     prefix_list = []
     for l in run_lines:
       (tool_cmd, filecheck_cmd) = tuple([cmd.strip() for cmd in l.split('|', 1)])
 
       if not tool_cmd.startswith(opt_basename + ' '):
-        print >>sys.stderr, 'WARNING: Skipping non-%s RUN line: %s' % (opt_basename, l)
+        print('WARNING: Skipping non-%s RUN line: %s' % (opt_basename, l), file=sys.stderr)
         continue
 
       if not filecheck_cmd.startswith('FileCheck '):
-        print >>sys.stderr, 'WARNING: Skipping non-FileChecked RUN line: ' + l
+        print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
         continue
 
       tool_cmd_args = tool_cmd[len(opt_basename):].strip()
@@ -119,8 +121,8 @@
         func_dict.update({prefix: dict()})
     for prefixes, opt_args in prefix_list:
       if args.verbose:
-        print >>sys.stderr, 'Extracted opt cmd: ' + opt_basename + ' ' + opt_args
-        print >>sys.stderr, 'Extracted FileCheck prefixes: ' + str(prefixes)
+        print('Extracted opt cmd: ' + opt_basename + ' ' + opt_args, file=sys.stderr)
+        print('Extracted FileCheck prefixes: ' + str(prefixes), file=sys.stderr)
 
       raw_tool_output = common.invoke_tool(args.opt_binary, opt_args, test)
       common.build_function_body_dictionary(
@@ -131,7 +133,7 @@
     is_in_function_start = False
     prefix_set = set([prefix for prefixes, _ in prefix_list for prefix in prefixes])
     if args.verbose:
-      print >>sys.stderr, 'Rewriting FileCheck prefixes: %s' % (prefix_set,)
+      print('Rewriting FileCheck prefixes: %s' % (prefix_set,), file=sys.stderr)
     output_lines = []
     output_lines.append(autogenerated_note)
 
@@ -178,7 +180,7 @@
       is_in_function = is_in_function_start = True
 
     if args.verbose:
-      print>>sys.stderr, 'Writing %d lines to %s...' % (len(output_lines), test)
+      print('Writing %d lines to %s...' % (len(output_lines), test), file=sys.stderr)
 
     with open(test, 'wb') as f:
       f.writelines([l + '\n' for l in output_lines])
diff --git a/llvm/utils/wciia.py b/llvm/utils/wciia.py
index eaa232f..4269db2 100755
--- a/llvm/utils/wciia.py
+++ b/llvm/utils/wciia.py
@@ -20,6 +20,7 @@
 
 """
 
+from __future__ import print_function
 import os
 
 code_owners = {}
@@ -97,7 +98,7 @@
 import sys
 
 if len(sys.argv) < 2:
-	print "usage " + sys.argv[0] + " file_or_folder"  
+	print("usage " + sys.argv[0] + " file_or_folder")
 	exit(-1)
 	
 # the path we are checking
@@ -105,13 +106,13 @@
 
 # check if this is real path
 if not os.path.exists(path):
-	print "path (" + path + ") does not exist"
+	print("path (" + path + ") does not exist")
 	exit(-1)
 	
 owners_name = find_owners(path)
 
 # be grammatically correct
-print "The owner(s) of the (" + path + ") is(are) : " + str(owners_name)
+print("The owner(s) of the (" + path + ") is(are) : " + str(owners_name))
 
 exit(0)
 
@@ -119,7 +120,7 @@
 # not yet used 
 root = "."
 for dir,subdirList,fileList in os.walk( root , topdown=False ) :
-   print "dir :" , dir
+   print("dir :" , dir)
    for fname in fileList :
-      print "-" , fname
-   print
+      print("-" , fname)
+   print()