From lattner at cs.uiuc.edu Mon Oct 4 00:20:30 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 00:20:30 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/X86/X86InstrInfo.td Message-ID: <200410040520.AAA25492@apoc.cs.uiuc.edu> Changes in directory llvm/lib/Target/X86: X86InstrInfo.td updated: 1.106 -> 1.107 --- Log message: Fix incorrect suffix --- Diffs of the changes: (+1 -1) Index: llvm/lib/Target/X86/X86InstrInfo.td diff -u llvm/lib/Target/X86/X86InstrInfo.td:1.106 llvm/lib/Target/X86/X86InstrInfo.td:1.107 --- llvm/lib/Target/X86/X86InstrInfo.td:1.106 Sun Oct 3 20:38:10 2004 +++ llvm/lib/Target/X86/X86InstrInfo.td Mon Oct 4 00:20:16 2004 @@ -1322,7 +1322,7 @@ def FLD80m : FPI<0xDB, MRM5m, ZeroArgFP, (ops f80mem:$src), "fld{t} $src">; def FILD16m : FPI<0xDF, MRM0m, ZeroArgFP, (ops i16mem:$src), "fild{s} $src">; def FILD32m : FPI<0xDB, MRM0m, ZeroArgFP, (ops i32mem:$src), "fild{l} $src">; -def FILD64m : FPI<0xDF, MRM5m, ZeroArgFP, (ops i64mem:$src), "fild{t} $src">; +def FILD64m : FPI<0xDF, MRM5m, ZeroArgFP, (ops i64mem:$src), "fild{ll} $src">; def FSTrr : FPI<0xD0, AddRegFrm, NotFP, (ops RST:$op), "fst $op">, DD; def FSTPrr : FPI<0xD8, AddRegFrm, NotFP, (ops RST:$op), "fstp $op">, DD; From reid at x10sys.com Mon Oct 4 02:05:18 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 02:05:18 -0500 Subject: [llvm-commits] CVS: llvm/configure Makefile.rules Makefile.config.in Message-ID: <200410040705.CAA27457@zion.cs.uiuc.edu> Changes in directory llvm: configure updated: 1.126 -> 1.127 Makefile.rules updated: 1.199 -> 1.200 Makefile.config.in updated: 1.31 -> 1.32 --- Log message: Provide support for auto-detection and use of compression libraries. --- Diffs of the changes: (+25 -7) Index: llvm/configure diff -u llvm/configure:1.126 llvm/configure:1.127 --- llvm/configure:1.126 Sat Oct 2 03:50:57 2004 +++ llvm/configure Mon Oct 4 02:05:05 2004 @@ -473,7 +473,7 @@ # include #endif" -ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS subdirs INSTALL_PROGRAM INSTALL_SCRIPT INSTALL_DATA build build_cpu build_vendor build_os host host_cpu host_vendor host_os target target_cpu target_vendor target_os OS LLVMGCCDIR ARCH CXX CXXFLAGS LDFLAGS CPPFLAGS ac_ct_CXX EXEEXT OBJEXT CC CFLAGS ac_ct_CC CPP ifGNUmake LEX LEXLIB LEX_OUTPUT_ROOT FLEX YACC BISON EGREP LN_S ECHO AR ac_ct_AR RANLIB ac_ct_RANLIB STRIP ac_ct_STRIP CXXCPP F77 FFLAGS ac_ct_F77 LIBTOOL DOT ETAGS ETAGSFLAGS PYTHON QMTEST ENDIAN ALLOCA MMAP_FILE ENABLE_OPTIMIZED JIT LLVMCC1 LLVMCC1PLUS SHLIBEXT LLVM_PREFIX LLVM_BINDIR LLVM_LIBDIR LLVM_DATADIR LLVM_DOCSDIR LLVM_ETCDIR LLVM_INCLUDEDIR LLVM_INFODIR LLVM_MANDIR LLV! M_CONFIGTIME LIBOBJS LTLIBOBJS' +ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS subdirs INSTALL_PROGRAM INSTALL_SCRIPT INSTALL_DATA build build_cpu build_vendor build_os host host_cpu host_vendor host_os target target_cpu target_vendor target_os OS LLVMGCCDIR ARCH CXX CXXFLAGS LDFLAGS CPPFLAGS ac_ct_CXX EXEEXT OBJEXT CC CFLAGS ac_ct_CC CPP ifGNUmake LEX LEXLIB LEX_OUTPUT_ROOT FLEX YACC BISON EGREP LN_S ECHO AR ac_ct_AR RANLIB ac_ct_RANLIB STRIP ac_ct_STRIP CXXCPP F77 FFLAGS ac_ct_F77 LIBTOOL DOT ETAGS ETAGSFLAGS PYTHON QMTEST HAVE_ZLIB HAVE_BZIP2 ENDIAN ALLOCA MMAP_FILE ENABLE_OPTIMIZED JIT LLVMCC1 LLVMCC1PLUS SHLIBEXT LLVM_PREFIX LLVM_BINDIR LLVM_LIBDIR LLVM_DATADIR LLVM_DOCSDIR LLVM_ETCDIR LLVM_INCLUDEDIR LLVM_IN! FODIR LLVM_MANDIR LLVM_CONFIGTIME LIBOBJS LTLIBOBJS' ac_subst_files='' # Initialize some variables set by options. @@ -19339,6 +19339,10 @@ zlib_found=0 fi +HAVE_ZLIB=$zlib_found + +HAVE_BZIP2=$bzip2_found + if test $zlib_found -eq 1 ; then cat >>confdefs.h <<\_ACEOF @@ -24853,6 +24857,8 @@ s, at ETAGSFLAGS@,$ETAGSFLAGS,;t t s, at PYTHON@,$PYTHON,;t t s, at QMTEST@,$QMTEST,;t t +s, at HAVE_ZLIB@,$HAVE_ZLIB,;t t +s, at HAVE_BZIP2@,$HAVE_BZIP2,;t t s, at ENDIAN@,$ENDIAN,;t t s, at ALLOCA@,$ALLOCA,;t t s, at MMAP_FILE@,$MMAP_FILE,;t t Index: llvm/Makefile.rules diff -u llvm/Makefile.rules:1.199 llvm/Makefile.rules:1.200 --- llvm/Makefile.rules:1.199 Tue Sep 28 09:52:58 2004 +++ llvm/Makefile.rules Mon Oct 4 02:05:06 2004 @@ -463,8 +463,8 @@ $(MKDIR) $(sysconfdir) install-config-files: $(sysconfdir) $(CONFIG_FILES) - $(VERB) echo Installing Configuration Files To $(sysconfdir) - $(VERB) for file in $(CONFIG_FILES); do \ + $(VERB)$(ECHO) Installing Configuration Files To $(sysconfdir) + $(VERB)for file in $(CONFIG_FILES); do \ $(INSTALL) $(SourceDir)/$${file} $(sysconfdir) ; \ done endif @@ -527,7 +527,7 @@ $(DESTDIR)$(bytecode_libdir)/lib$(LIBRARYNAME).bc: $(LIBNAME_BC) $(DESTDIR)$(bytecode_libdir) @${ECHO} ======= Installing $(LIBRARYNAME) bytecode library ======= - cp $< $@ + $(VERB)cp $< $@ # Does the library want a .o version built? ifndef DONT_BUILD_RELINKED @@ -593,7 +593,7 @@ # $(LIBNAME_AO): $(ObjectsO) $(LibSubDirs) $(DESTLIBRELEASE)/.dir @${ECHO} Linking $(LIBRARYNAME) archive release library - @$(RM) -f $@ + $(VERB)$(RM) -f $@ $(VERB) $(Link) -03 -o $@ $(ObjectsO) $(LibSubDirs) -static @${ECHO} Finished building $(LIBRARYNAME) archive release library ======= @@ -656,6 +656,13 @@ # ifdef TOOLNAME +# Handle compression libraries automatically +ifeq ($(HAVE_BZIP2),1) +USEDLIBS += bz2.a +endif +ifeq ($(HAVE_ZLIB),1) +USEDLIBS += z.a +endif # TOOLEXENAME* - These compute the output filenames to generate... TOOLEXENAME_G := $(DESTTOOLDEBUG)/$(TOOLNAME) TOOLEXENAME_O := $(DESTTOOLRELEASE)/$(TOOLNAME) @@ -728,8 +735,9 @@ @${ECHO} ======= Finished building $(TOOLNAME) profile executable ======= install:: $(TOOLEXENAMES) - $(MKDIR) $(DESTDIR)$(bindir) - $(LIBTOOL) --mode=install $(INSTALL_PROGRAM) -c -m 0755 $(TOOLEXENAMES) $(DESTDIR)$(bindir)/$(TOOLNAME) + @${ECHO} Installing $(TOOLEXENAMES) to $(DESTDIR)$(bindir) + $(VERB)$(MKDIR) $(DESTDIR)$(bindir) + $(VERB)$(LIBTOOL) --mode=install $(INSTALL_PROGRAM) -c -m 0755 $(TOOLEXENAMES) $(DESTDIR)$(bindir)/$(TOOLNAME) endif Index: llvm/Makefile.config.in diff -u llvm/Makefile.config.in:1.31 llvm/Makefile.config.in:1.32 --- llvm/Makefile.config.in:1.31 Tue Sep 7 12:34:34 2004 +++ llvm/Makefile.config.in Mon Oct 4 02:05:06 2004 @@ -155,6 +155,10 @@ SourceDir=$(BUILD_SRC_DIR) endif +# Handle configured libraries +HAVE_BZIP2 := @HAVE_BZIP2@ +HAVE_ZILB := @HAVE_ZLIB@ + # Installation directories, as provided by the configure script. exec_prefix = @exec_prefix@ prefix = @prefix@ From reid at x10sys.com Mon Oct 4 02:05:18 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 02:05:18 -0500 Subject: [llvm-commits] CVS: llvm/autoconf/configure.ac Message-ID: <200410040705.CAA27452@zion.cs.uiuc.edu> Changes in directory llvm/autoconf: configure.ac updated: 1.120 -> 1.121 --- Log message: Provide support for auto-detection and use of compression libraries. --- Diffs of the changes: (+2 -0) Index: llvm/autoconf/configure.ac diff -u llvm/autoconf/configure.ac:1.120 llvm/autoconf/configure.ac:1.121 --- llvm/autoconf/configure.ac:1.120 Sat Oct 2 03:50:58 2004 +++ llvm/autoconf/configure.ac Mon Oct 4 02:05:07 2004 @@ -250,6 +250,8 @@ dnl Check for bzip2 and zlib compression libraries needed for archive reading/writing AC_CHECK_LIB(bz2,BZ2_bzCompressInit,[bzip2_found=1],[bzip2_found=0]) AC_CHECK_LIB(z,gzopen,[zlib_found=1],[zlib_found=0]) +AC_SUBST([HAVE_ZLIB],$zlib_found) +AC_SUBST([HAVE_BZIP2],$bzip2_found) if test $zlib_found -eq 1 ; then AC_DEFINE([HAVE_ZLIB],[1],[Define if zlib library is available on this platform.]) fi From lattner at cs.uiuc.edu Mon Oct 4 02:09:01 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 02:09:01 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/X86/X86InstrInfo.td Message-ID: <200410040709.CAA19807@apoc.cs.uiuc.edu> Changes in directory llvm/lib/Target/X86: X86InstrInfo.td updated: 1.107 -> 1.108 --- Log message: Apparently the GNU assembler has a HUGE hack to be compatible with really old and broken AT&T syntax assemblers. The problem with this hack is that *SOME* forms of the fdiv and fsub instructions have the 'r' bit inverted. This was a real pain to figure out, but is trivially easy to support: thus we are now bug compatible with gas and gcc. --- Diffs of the changes: (+12 -9) Index: llvm/lib/Target/X86/X86InstrInfo.td diff -u llvm/lib/Target/X86/X86InstrInfo.td:1.107 llvm/lib/Target/X86/X86InstrInfo.td:1.108 --- llvm/lib/Target/X86/X86InstrInfo.td:1.107 Mon Oct 4 00:20:16 2004 +++ llvm/lib/Target/X86/X86InstrInfo.td Mon Oct 4 02:08:46 2004 @@ -369,7 +369,7 @@ def CBW : I<0x98, RawFrm, (ops), "{cbtw|cbw}">, Imp<[AL],[AH]>; // AX = signext(AL) def CWD : I<0x99, RawFrm, (ops), - "{cwtl|cwd}">, Imp<[AX],[DX]>; // DX:AX = signext(AX) + "{cwtd|cwd}">, Imp<[AX],[DX]>; // DX:AX = signext(AX) def CDQ : I<0x99, RawFrm, (ops), "{cltd|cdq}">, Imp<[EAX],[EDX]>; // EDX:EAX = signext(EAX) @@ -1372,19 +1372,22 @@ def FADDPrST0 : FPrST0PInst<0xC0, (ops RST:$op), "faddp $op">; +// NOTE: GAS and apparently all other AT&T style assemblers have a broken notion +// of some of the 'reverse' forms of the fsub and fdiv instructions. As such, +// we have to put some 'r's in and take them out of wierd places. def FSUBRST0r : FPST0rInst <0xE8, (ops RST:$op), "fsubr $op">; def FSUBrST0 : FPrST0Inst <0xE8, (ops RST:$op), - "fsub {%ST(0), $op|$op, %ST(0)}">; + "fsub{r} {%ST(0), $op|$op, %ST(0)}">; def FSUBPrST0 : FPrST0PInst<0xE8, (ops RST:$op), - "fsubp $op">; + "fsub{r}p $op">; def FSUBST0r : FPST0rInst <0xE0, (ops RST:$op), "fsub $op">; def FSUBRrST0 : FPrST0Inst <0xE0, (ops RST:$op), - "fsubr {%ST(0), $op|$op, %ST(0)}">; + "fsub{|r} {%ST(0), $op|$op, %ST(0)}">; def FSUBRPrST0 : FPrST0PInst<0xE0, (ops RST:$op), - "fsubrp $op">; + "fsub{|r}p $op">; def FMULST0r : FPST0rInst <0xC8, (ops RST:$op), "fmul $op">; @@ -1396,16 +1399,16 @@ def FDIVRST0r : FPST0rInst <0xF8, (ops RST:$op), "fdivr $op">; def FDIVrST0 : FPrST0Inst <0xF8, (ops RST:$op), - "fdiv {%ST(0), $op|$op, %ST(0)}">; + "fdiv{r} {%ST(0), $op|$op, %ST(0)}">; def FDIVPrST0 : FPrST0PInst<0xF8, (ops RST:$op), - "fdivp $op">; + "fdiv{r}p $op">; def FDIVST0r : FPST0rInst <0xF0, (ops RST:$op), // ST(0) = ST(0) / ST(i) "fdiv $op">; def FDIVRrST0 : FPrST0Inst <0xF0, (ops RST:$op), // ST(i) = ST(0) / ST(i) - "fdivr {%ST(0), $op|$op, %ST(0)}">; + "fdiv{|r} {%ST(0), $op|$op, %ST(0)}">; def FDIVRPrST0 : FPrST0PInst<0xF0, (ops RST:$op), // ST(i) = ST(0) / ST(i), pop - "fdivrp $op">; + "fdiv{|r}p $op">; // Floating point compares def FUCOMr : FPI<0xE0, AddRegFrm, CompareFP, // FPSW = cmp ST(0) with ST(i) From lattner at cs.uiuc.edu Mon Oct 4 02:23:20 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 02:23:20 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/X86/X86InstrInfo.td Message-ID: <200410040723.CAA23402@apoc.cs.uiuc.edu> Changes in directory llvm/lib/Target/X86: X86InstrInfo.td updated: 1.108 -> 1.109 --- Log message: Convert some missed patterns to support AT&T style --- Diffs of the changes: (+8 -8) Index: llvm/lib/Target/X86/X86InstrInfo.td diff -u llvm/lib/Target/X86/X86InstrInfo.td:1.108 llvm/lib/Target/X86/X86InstrInfo.td:1.109 --- llvm/lib/Target/X86/X86InstrInfo.td:1.108 Mon Oct 4 02:08:46 2004 +++ llvm/lib/Target/X86/X86InstrInfo.td Mon Oct 4 02:23:07 2004 @@ -665,21 +665,21 @@ "or{l} {$src2, $dst|$dst, $src2}">; let isTwoAddress = 0 in { def OR8mr : I<0x08, MRMDestMem, (ops i8mem:$dst, R8:$src), - "or{b} $dst, $src">; + "or{b} {$src, $dst|$dst, $src}">; def OR16mr : I<0x09, MRMDestMem, (ops i16mem:$dst, R16:$src), - "or{w} $dst, $src">, OpSize; + "or{w} {$src, $dst|$dst, $src}">, OpSize; def OR32mr : I<0x09, MRMDestMem, (ops i32mem:$dst, R32:$src), - "or{l} $dst, $src">; + "or{l} {$src, $dst|$dst, $src}">; def OR8mi : Ii8<0x80, MRM1m, (ops i8mem :$dst, i8imm:$src), - "or{b} $dst, $src">; + "or{b} {$src, $dst|$dst, $src}">; def OR16mi : Ii16<0x81, MRM1m, (ops i16mem:$dst, i16imm:$src), - "or{w} $dst, $src">, OpSize; + "or{w} {$src, $dst|$dst, $src}">, OpSize; def OR32mi : Ii32<0x81, MRM1m, (ops i32mem:$dst, i32imm:$src), - "or{l} $dst, $src">; + "or{l} {$src, $dst|$dst, $src}">; def OR16mi8 : Ii8<0x83, MRM1m, (ops i16mem:$dst, i8imm:$src), - "or{w} $dst, $src">, OpSize; + "or{w} {$src, $dst|$dst, $src}">, OpSize; def OR32mi8 : Ii8<0x83, MRM1m, (ops i32mem:$dst, i8imm:$src), - "or{l} $dst, $src">; + "or{l} {$src, $dst|$dst, $src}">; } From lattner at cs.uiuc.edu Mon Oct 4 02:24:59 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 02:24:59 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/X86/X86AsmPrinter.cpp Message-ID: <200410040724.CAA23559@apoc.cs.uiuc.edu> Changes in directory llvm/lib/Target/X86: X86AsmPrinter.cpp updated: 1.122 -> 1.123 --- Log message: Add support for emitting AT&T style .s files, and make it the default. Users may now choose their output format with the -x86-asm-syntax={intel|att} flag. --- Diffs of the changes: (+307 -128) Index: llvm/lib/Target/X86/X86AsmPrinter.cpp diff -u llvm/lib/Target/X86/X86AsmPrinter.cpp:1.122 llvm/lib/Target/X86/X86AsmPrinter.cpp:1.123 --- llvm/lib/Target/X86/X86AsmPrinter.cpp:1.122 Sun Oct 3 15:36:57 2004 +++ llvm/lib/Target/X86/X86AsmPrinter.cpp Mon Oct 4 02:24:48 2004 @@ -34,6 +34,127 @@ #include "llvm/Support/CommandLine.h" using namespace llvm; +static bool isScale(const MachineOperand &MO) { + return MO.isImmediate() && + (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 || + MO.getImmedValue() == 4 || MO.getImmedValue() == 8); +} + +static bool isMem(const MachineInstr *MI, unsigned Op) { + if (MI->getOperand(Op).isFrameIndex()) return true; + if (MI->getOperand(Op).isConstantPoolIndex()) return true; + return Op+4 <= MI->getNumOperands() && + MI->getOperand(Op ).isRegister() && isScale(MI->getOperand(Op+1)) && + MI->getOperand(Op+2).isRegister() && MI->getOperand(Op+3).isImmediate(); +} + +// SwitchSection - Switch to the specified section of the executable if we are +// not already in it! +// +static void SwitchSection(std::ostream &OS, std::string &CurSection, + const char *NewSection) { + if (CurSection != NewSection) { + CurSection = NewSection; + if (!CurSection.empty()) + OS << "\t" << NewSection << "\n"; + } +} + +namespace { + struct X86SharedAsmPrinter : public AsmPrinter { + X86SharedAsmPrinter(std::ostream &O, TargetMachine &TM) + : AsmPrinter(O, TM) { } + + void printConstantPool(MachineConstantPool *MCP); + bool doFinalization(Module &M); + }; +} + +/// printConstantPool - Print to the current output stream assembly +/// representations of the constants in the constant pool MCP. This is +/// used to print out constants which have been "spilled to memory" by +/// the code generator. +/// +void X86SharedAsmPrinter::printConstantPool(MachineConstantPool *MCP) { + const std::vector &CP = MCP->getConstants(); + const TargetData &TD = TM.getTargetData(); + + if (CP.empty()) return; + + for (unsigned i = 0, e = CP.size(); i != e; ++i) { + O << "\t.section .rodata\n"; + emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType())); + O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString + << *CP[i] << "\n"; + emitGlobalConstant(CP[i]); + } +} + +bool X86SharedAsmPrinter::doFinalization(Module &M) { + const TargetData &TD = TM.getTargetData(); + std::string CurSection; + + // Print out module-level global variables here. + for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) + if (I->hasInitializer()) { // External global require no code + O << "\n\n"; + std::string name = Mang->getValueName(I); + Constant *C = I->getInitializer(); + unsigned Size = TD.getTypeSize(C->getType()); + unsigned Align = TD.getTypeAlignmentShift(C->getType()); + + if (C->isNullValue() && + (I->hasLinkOnceLinkage() || I->hasInternalLinkage() || + I->hasWeakLinkage() /* FIXME: Verify correct */)) { + SwitchSection(O, CurSection, ".data"); + if (I->hasInternalLinkage()) + O << "\t.local " << name << "\n"; + + O << "\t.comm " << name << "," << TD.getTypeSize(C->getType()) + << "," << (1 << Align); + O << "\t\t# "; + WriteAsOperand(O, I, true, true, &M); + O << "\n"; + } else { + switch (I->getLinkage()) { + case GlobalValue::LinkOnceLinkage: + case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak. + // Nonnull linkonce -> weak + O << "\t.weak " << name << "\n"; + SwitchSection(O, CurSection, ""); + O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\", at progbits\n"; + break; + case GlobalValue::AppendingLinkage: + // FIXME: appending linkage variables should go into a section of + // their name or something. For now, just emit them as external. + case GlobalValue::ExternalLinkage: + // If external or appending, declare as a global symbol + O << "\t.globl " << name << "\n"; + // FALL THROUGH + case GlobalValue::InternalLinkage: + if (C->isNullValue()) + SwitchSection(O, CurSection, ".bss"); + else + SwitchSection(O, CurSection, ".data"); + break; + } + + emitAlignment(Align); + O << "\t.type " << name << ", at object\n"; + O << "\t.size " << name << "," << Size << "\n"; + O << name << ":\t\t\t\t# "; + WriteAsOperand(O, I, true, true, &M); + O << " = "; + WriteAsOperand(O, C, false, false, &M); + O << "\n"; + emitGlobalConstant(C); + } + } + + AsmPrinter::doFinalization(M); + return false; // success +} + namespace { Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed"); enum AsmWriterFlavor { att, intel }; @@ -42,10 +163,10 @@ AsmWriterFlavor("x86-asm-syntax", cl::desc("Choose style of code to emit from X86 backend:"), cl::values( - clEnumVal(att, " Emit AT&T Style"), - clEnumVal(intel, " Emit Intel Style"), + clEnumVal(att, " Emit AT&T-style assembly"), + clEnumVal(intel, " Emit Intel-style assembly"), clEnumValEnd), - cl::init(intel)); + cl::init(att)); struct GasBugWorkaroundEmitter : public MachineCodeEmitter { GasBugWorkaroundEmitter(std::ostream& o) @@ -77,11 +198,12 @@ bool firstByte; }; - struct X86IntelAsmPrinter : public AsmPrinter { - X86IntelAsmPrinter(std::ostream &O, TargetMachine &TM) : AsmPrinter(O, TM) { } + struct X86IntelAsmPrinter : public X86SharedAsmPrinter { + X86IntelAsmPrinter(std::ostream &O, TargetMachine &TM) + : X86SharedAsmPrinter(O, TM) { } virtual const char *getPassName() const { - return "X86 Assembly Printer"; + return "X86 Intel-Style Assembly Printer"; } /// printInstruction - This method is automatically generated by tablegen @@ -125,52 +247,16 @@ void printMachineInstruction(const MachineInstr *MI); void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false); void printMemReference(const MachineInstr *MI, unsigned Op); - void printConstantPool(MachineConstantPool *MCP); bool runOnMachineFunction(MachineFunction &F); bool doInitialization(Module &M); - bool doFinalization(Module &M); }; } // end of anonymous namespace -/// createX86CodePrinterPass - Returns a pass that prints the X86 -/// assembly code for a MachineFunction to the given output stream, -/// using the given target machine description. This should work -/// regardless of whether the function is in SSA form. -/// -FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){ - if (AsmWriterFlavor != intel) { - std::cerr << "AT&T syntax not fully implemented yet!\n"; - abort(); - } - - return new X86IntelAsmPrinter(o, tm); -} - // Include the auto-generated portion of the assembly writer. #include "X86GenIntelAsmWriter.inc" -/// printConstantPool - Print to the current output stream assembly -/// representations of the constants in the constant pool MCP. This is -/// used to print out constants which have been "spilled to memory" by -/// the code generator. -/// -void X86IntelAsmPrinter::printConstantPool(MachineConstantPool *MCP) { - const std::vector &CP = MCP->getConstants(); - const TargetData &TD = TM.getTargetData(); - - if (CP.empty()) return; - - for (unsigned i = 0, e = CP.size(); i != e; ++i) { - O << "\t.section .rodata\n"; - emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType())); - O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString - << *CP[i] << "\n"; - emitGlobalConstant(CP[i]); - } -} - /// runOnMachineFunction - This uses the printMachineInstruction() /// method to print assembly for each instruction. /// @@ -206,24 +292,8 @@ return false; } -static bool isScale(const MachineOperand &MO) { - return MO.isImmediate() && - (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 || - MO.getImmedValue() == 4 || MO.getImmedValue() == 8); -} - -static bool isMem(const MachineInstr *MI, unsigned Op) { - if (MI->getOperand(Op).isFrameIndex()) return true; - if (MI->getOperand(Op).isConstantPoolIndex()) return true; - return Op+4 <= MI->getNumOperands() && - MI->getOperand(Op ).isRegister() && isScale(MI->getOperand(Op+1)) && - MI->getOperand(Op+2).isRegister() && MI->getOperand(Op+3).isImmediate(); -} - - - void X86IntelAsmPrinter::printOp(const MachineOperand &MO, - bool elideOffsetKeyword /* = false */) { + bool elideOffsetKeyword /* = false */) { const MRegisterInfo &RI = *TM.getRegisterInfo(); switch (MO.getType()) { case MachineOperand::MO_VirtualRegister: @@ -268,7 +338,7 @@ } } -void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op) { +void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op){ assert(isMem(MI, Op) && "Invalid memory reference!"); if (MI->getOperand(Op).isFrameIndex()) { @@ -378,79 +448,188 @@ return false; } -// SwitchSection - Switch to the specified section of the executable if we are -// not already in it! -// -static void SwitchSection(std::ostream &OS, std::string &CurSection, - const char *NewSection) { - if (CurSection != NewSection) { - CurSection = NewSection; - if (!CurSection.empty()) - OS << "\t" << NewSection << "\n"; + + +namespace { + struct X86ATTAsmPrinter : public X86SharedAsmPrinter { + X86ATTAsmPrinter(std::ostream &O, TargetMachine &TM) + : X86SharedAsmPrinter(O, TM) { } + + virtual const char *getPassName() const { + return "X86 AT&T-Style Assembly Printer"; + } + + /// printInstruction - This method is automatically generated by tablegen + /// from the instruction set description. This method returns true if the + /// machine instruction was sufficiently described to print it, otherwise it + /// returns false. + bool printInstruction(const MachineInstr *MI); + + // This method is used by the tablegen'erated instruction printer. + void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){ + printOp(MI->getOperand(OpNo)); + } + + void printCallOperand(const MachineInstr *MI, unsigned OpNo, + MVT::ValueType VT) { + printOp(MI->getOperand(OpNo), true); // Don't print '$' prefix. + } + + void printMemoryOperand(const MachineInstr *MI, unsigned OpNo, + MVT::ValueType VT) { + printMemReference(MI, OpNo); + } + + void printMachineInstruction(const MachineInstr *MI); + void printOp(const MachineOperand &MO, bool isCallOperand = false); + void printMemReference(const MachineInstr *MI, unsigned Op); + bool runOnMachineFunction(MachineFunction &F); + }; +} // end of anonymous namespace + + +// Include the auto-generated portion of the assembly writer. +#include "X86GenATTAsmWriter.inc" + + +/// runOnMachineFunction - This uses the printMachineInstruction() +/// method to print assembly for each instruction. +/// +bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) { + setupMachineFunction(MF); + O << "\n\n"; + + // Print out constants referenced by the function + printConstantPool(MF.getConstantPool()); + + // Print out labels for the function. + O << "\t.text\n"; + emitAlignment(4); + O << "\t.globl\t" << CurrentFnName << "\n"; + O << "\t.type\t" << CurrentFnName << ", @function\n"; + O << CurrentFnName << ":\n"; + + // Print out code for the function. + for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); + I != E; ++I) { + // Print a label for the basic block. + O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t" + << CommentString << " " << I->getBasicBlock()->getName() << "\n"; + for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end(); + II != E; ++II) { + // Print the assembly for the instruction. + O << "\t"; + printMachineInstruction(II); + } } + + // We didn't modify anything. + return false; } -bool X86IntelAsmPrinter::doFinalization(Module &M) { - const TargetData &TD = TM.getTargetData(); - std::string CurSection; +void X86ATTAsmPrinter::printOp(const MachineOperand &MO, bool isCallOp) { + const MRegisterInfo &RI = *TM.getRegisterInfo(); + switch (MO.getType()) { + case MachineOperand::MO_VirtualRegister: + case MachineOperand::MO_MachineRegister: + assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) && + "Virtual registers should not make it this far!"); + O << '%'; + for (const char *Name = RI.get(MO.getReg()).Name; *Name; ++Name) + O << (char)tolower(*Name); + return; - // Print out module-level global variables here. - for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) - if (I->hasInitializer()) { // External global require no code - O << "\n\n"; - std::string name = Mang->getValueName(I); - Constant *C = I->getInitializer(); - unsigned Size = TD.getTypeSize(C->getType()); - unsigned Align = TD.getTypeAlignmentShift(C->getType()); + case MachineOperand::MO_SignExtendedImmed: + case MachineOperand::MO_UnextendedImmed: + O << '$' << (int)MO.getImmedValue(); + return; + case MachineOperand::MO_MachineBasicBlock: { + MachineBasicBlock *MBBOp = MO.getMachineBasicBlock(); + O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction()) + << "_" << MBBOp->getNumber () << "\t# " + << MBBOp->getBasicBlock ()->getName (); + return; + } + case MachineOperand::MO_PCRelativeDisp: + std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs"; + abort (); + return; + case MachineOperand::MO_GlobalAddress: + if (!isCallOp) O << '$'; + O << Mang->getValueName(MO.getGlobal()); + return; + case MachineOperand::MO_ExternalSymbol: + if (!isCallOp) O << '$'; + O << MO.getSymbolName(); + return; + default: + O << ""; return; + } +} - if (C->isNullValue() && - (I->hasLinkOnceLinkage() || I->hasInternalLinkage() || - I->hasWeakLinkage() /* FIXME: Verify correct */)) { - SwitchSection(O, CurSection, ".data"); - if (I->hasInternalLinkage()) - O << "\t.local " << name << "\n"; - - O << "\t.comm " << name << "," << TD.getTypeSize(C->getType()) - << "," << (1 << Align); - O << "\t\t# "; - WriteAsOperand(O, I, true, true, &M); - O << "\n"; - } else { - switch (I->getLinkage()) { - case GlobalValue::LinkOnceLinkage: - case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak. - // Nonnull linkonce -> weak - O << "\t.weak " << name << "\n"; - SwitchSection(O, CurSection, ""); - O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\", at progbits\n"; - break; - case GlobalValue::AppendingLinkage: - // FIXME: appending linkage variables should go into a section of - // their name or something. For now, just emit them as external. - case GlobalValue::ExternalLinkage: - // If external or appending, declare as a global symbol - O << "\t.globl " << name << "\n"; - // FALL THROUGH - case GlobalValue::InternalLinkage: - if (C->isNullValue()) - SwitchSection(O, CurSection, ".bss"); - else - SwitchSection(O, CurSection, ".data"); - break; - } +void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op){ + assert(isMem(MI, Op) && "Invalid memory reference!"); - emitAlignment(Align); - O << "\t.type " << name << ", at object\n"; - O << "\t.size " << name << "," << Size << "\n"; - O << name << ":\t\t\t\t# "; - WriteAsOperand(O, I, true, true, &M); - O << " = "; - WriteAsOperand(O, C, false, false, &M); - O << "\n"; - emitGlobalConstant(C); - } - } + if (MI->getOperand(Op).isFrameIndex()) { + O << "[frame slot #" << MI->getOperand(Op).getFrameIndex(); + if (MI->getOperand(Op+3).getImmedValue()) + O << " + " << MI->getOperand(Op+3).getImmedValue(); + O << "]"; + return; + } else if (MI->getOperand(Op).isConstantPoolIndex()) { + O << ".CPI" << CurrentFnName << "_" + << MI->getOperand(Op).getConstantPoolIndex(); + if (MI->getOperand(Op+3).getImmedValue()) + O << " + " << MI->getOperand(Op+3).getImmedValue(); + return; + } - AsmPrinter::doFinalization(M); - return false; // success + const MachineOperand &BaseReg = MI->getOperand(Op); + int ScaleVal = MI->getOperand(Op+1).getImmedValue(); + const MachineOperand &IndexReg = MI->getOperand(Op+2); + int DispVal = MI->getOperand(Op+3).getImmedValue(); + + if (DispVal) O << DispVal; + + O << "("; + if (BaseReg.getReg()) + printOp(BaseReg); + + if (IndexReg.getReg()) { + O << ","; + printOp(IndexReg); + if (ScaleVal != 1) + O << "," << ScaleVal; + } + + O << ")"; +} + + +/// printMachineInstruction -- Print out a single X86 LLVM instruction +/// MI in Intel syntax to the current output stream. +/// +void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) { + ++EmittedInsts; + // Call the autogenerated instruction printer routines. + if (!printInstruction(MI)) { + MI->dump(); + assert(0 && "Do not know how to print this instruction!"); + abort(); + } +} + + +/// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code +/// for a MachineFunction to the given output stream, using the given target +/// machine description. +/// +FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){ + switch (AsmWriterFlavor) { + default: assert(0 && "Unknown asm flavor!"); + case intel: + return new X86IntelAsmPrinter(o, tm); + case att: + return new X86ATTAsmPrinter(o, tm); + } } From lattner at cs.uiuc.edu Mon Oct 4 02:31:19 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 02:31:19 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/X86/X86AsmPrinter.cpp Message-ID: <200410040731.CAA25514@apoc.cs.uiuc.edu> Changes in directory llvm/lib/Target/X86: X86AsmPrinter.cpp updated: 1.123 -> 1.124 --- Log message: * Prune #includes * Update comments * Rearrange code a bit * Finally ELIMINATE the GAS workaround emitter for Intel mode. woot! --- Diffs of the changes: (+27 -101) Index: llvm/lib/Target/X86/X86AsmPrinter.cpp diff -u llvm/lib/Target/X86/X86AsmPrinter.cpp:1.123 llvm/lib/Target/X86/X86AsmPrinter.cpp:1.124 --- llvm/lib/Target/X86/X86AsmPrinter.cpp:1.123 Mon Oct 4 02:24:48 2004 +++ llvm/lib/Target/X86/X86AsmPrinter.cpp Mon Oct 4 02:31:08 2004 @@ -8,32 +8,48 @@ //===----------------------------------------------------------------------===// // // This file contains a printer that converts from our internal representation -// of machine-dependent LLVM code to Intel-format assembly language. This -// printer is the output mechanism used by `llc' and `lli -print-machineinstrs' -// on X86. +// of machine-dependent LLVM code to Intel and AT&T format assembly +// language. This printer is the output mechanism used by `llc' and `lli +// -print-machineinstrs' on X86. // //===----------------------------------------------------------------------===// #include "X86.h" -#include "X86InstrInfo.h" #include "X86TargetMachine.h" -#include "llvm/Constants.h" -#include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Assembly/Writer.h" #include "llvm/CodeGen/AsmPrinter.h" -#include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/MachineFunctionPass.h" -#include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/ValueTypes.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/Mangler.h" #include "llvm/ADT/Statistic.h" -#include "llvm/ADT/StringExtras.h" #include "llvm/Support/CommandLine.h" using namespace llvm; +namespace { + Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed"); + enum AsmWriterFlavor { att, intel }; + + cl::opt + AsmWriterFlavor("x86-asm-syntax", + cl::desc("Choose style of code to emit from X86 backend:"), + cl::values( + clEnumVal(att, " Emit AT&T-style assembly"), + clEnumVal(intel, " Emit Intel-style assembly"), + clEnumValEnd), + cl::init(att)); + + struct X86SharedAsmPrinter : public AsmPrinter { + X86SharedAsmPrinter(std::ostream &O, TargetMachine &TM) + : AsmPrinter(O, TM) { } + + void printConstantPool(MachineConstantPool *MCP); + bool doFinalization(Module &M); + }; +} + static bool isScale(const MachineOperand &MO) { return MO.isImmediate() && (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 || @@ -60,16 +76,6 @@ } } -namespace { - struct X86SharedAsmPrinter : public AsmPrinter { - X86SharedAsmPrinter(std::ostream &O, TargetMachine &TM) - : AsmPrinter(O, TM) { } - - void printConstantPool(MachineConstantPool *MCP); - bool doFinalization(Module &M); - }; -} - /// printConstantPool - Print to the current output stream assembly /// representations of the constants in the constant pool MCP. This is /// used to print out constants which have been "spilled to memory" by @@ -156,48 +162,6 @@ } namespace { - Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed"); - enum AsmWriterFlavor { att, intel }; - - cl::opt - AsmWriterFlavor("x86-asm-syntax", - cl::desc("Choose style of code to emit from X86 backend:"), - cl::values( - clEnumVal(att, " Emit AT&T-style assembly"), - clEnumVal(intel, " Emit Intel-style assembly"), - clEnumValEnd), - cl::init(att)); - - struct GasBugWorkaroundEmitter : public MachineCodeEmitter { - GasBugWorkaroundEmitter(std::ostream& o) - : O(o), OldFlags(O.flags()), firstByte(true) { - O << std::hex; - } - - ~GasBugWorkaroundEmitter() { - O.flags(OldFlags); - } - - virtual void emitByte(unsigned char B) { - if (!firstByte) O << "\n\t"; - firstByte = false; - O << ".byte 0x" << (unsigned) B; - } - - // These should never be called - virtual void emitWord(unsigned W) { assert(0); } - virtual uint64_t getGlobalValueAddress(GlobalValue *V) { abort(); } - virtual uint64_t getGlobalValueAddress(const std::string &Name) { abort(); } - virtual uint64_t getConstantPoolEntryAddress(unsigned Index) { abort(); } - virtual uint64_t getCurrentPCValue() { abort(); } - virtual uint64_t forceCompilationOf(Function *F) { abort(); } - - private: - std::ostream& O; - std::ios::fmtflags OldFlags; - bool firstByte; - }; - struct X86IntelAsmPrinter : public X86SharedAsmPrinter { X86IntelAsmPrinter(std::ostream &O, TargetMachine &TM) : X86SharedAsmPrinter(O, TM) { } @@ -396,42 +360,8 @@ void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) { ++EmittedInsts; - // gas bugs: - // - // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]" is misassembled - // by gas in intel_syntax mode as its 32-bit equivalent "fstp DWORD PTR - // [...]". Workaround: Output the raw opcode bytes instead of the instruction. - // - // The 80-bit FP load instruction "fld XWORD PTR [...]" is misassembled by gas - // in intel_syntax mode as its 32-bit equivalent "fld DWORD PTR - // [...]". Workaround: Output the raw opcode bytes instead of the instruction. - // - // gas intel_syntax mode treats "fild QWORD PTR [...]" as an invalid opcode, - // saying "64 bit operations are only supported in 64 bit modes." libopcodes - // disassembles it as "fild DWORD PTR [...]", which is wrong. Workaround: - // Output the raw opcode bytes instead of the instruction. - // - // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an invalid opcode, - // saying "64 bit operations are only supported in 64 bit modes." libopcodes - // disassembles it as "fistpll DWORD PTR [...]", which is wrong. Workaround: - // Output the raw opcode bytes instead of the instruction. - switch (MI->getOpcode()) { - case X86::FSTP80m: - case X86::FLD80m: - case X86::FILD64m: - case X86::FISTP64m: - GasBugWorkaroundEmitter gwe(O); - X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI); - O << "\t# "; - } - // Call the autogenerated instruction printer routines. - bool Handled = printInstruction(MI); - if (!Handled) { - MI->dump(); - assert(0 && "Do not know how to print this instruction!"); - abort(); - } + printInstruction(MI); } bool X86IntelAsmPrinter::doInitialization(Module &M) { @@ -612,11 +542,7 @@ void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) { ++EmittedInsts; // Call the autogenerated instruction printer routines. - if (!printInstruction(MI)) { - MI->dump(); - assert(0 && "Do not know how to print this instruction!"); - abort(); - } + printInstruction(MI); } From reid at x10sys.com Mon Oct 4 05:49:52 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 05:49:52 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/Support/Compressor.h Message-ID: <200410041049.FAA31506@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/Support: Compressor.h added (r1.1) --- Log message: First version of a support utility to provide generalized compression in LLVM that handles availability and unavailability of bzip2 and zlib. --- Diffs of the changes: (+99 -0) Index: llvm/include/llvm/Support/Compressor.h diff -c /dev/null llvm/include/llvm/Support/Compressor.h:1.1 *** /dev/null Mon Oct 4 05:49:51 2004 --- llvm/include/llvm/Support/Compressor.h Mon Oct 4 05:49:41 2004 *************** *** 0 **** --- 1,99 ---- + //===- llvm/Support/Compressor.h --------------------------------*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Reid Spencer and is distributed under the + // University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file declares the llvm::Compressor class. + // + //===----------------------------------------------------------------------===// + + #ifndef LLVM_SUPPORT_COMPRESSOR_H + #define LLVM_SUPPORT_COMPRESSOR_H + + #include + + namespace llvm { + + /// This class provides an abstraction for compressing a block of memory using + /// a standard compression utility such as bzip2 or libz. This interface + /// allos us to abstraction the notion of compression and deal with alternate + /// compression scheme availability depending on the configured platform. This + /// facility will always favor a bzip2 implementation if its available. + /// Otherwise, libz will be used if its available. If neither zlib nor bzip2 + /// are available, a very simple algorithm provided by the Compressor class + /// will be used The type of compression used can be determined by inspecting + /// the first byte of the compressed output. ASCII values '0', '1', and '2', + /// denote the compression type as given in the Algorithm enumeration below. + /// The Compressor is intended for use with memory mapped files where the + /// entire data block to be compressed or decompressed is available in + /// memory. Output, however, can be gathered in repeated calls to a callback. + /// @since 1.4 + /// @brief An abstraction for memory to memory data compression + class Compressor { + /// @name Types + /// @{ + public: + enum Algorithm { + COMP_TYPE_SIMPLE = '0', ///< Use simple but ubiquitous algorithm + COMP_TYPE_ZLIB = '1', ///< Use zlib algorithm, if available + COMP_TYPE_BZIP2 = '2', ///< Use bzip2 algorithm (preferred) + }; + + /// A callback function type used by the Compressor to get the next chunk + /// of data to which (de)compressed output will be written. This function + /// must be written by the caller to provide the buffering of the output + /// data. + /// @returns 0 for success, 1 for failure + /// @throws nothing + /// @brief Output callback function type + typedef unsigned (OutputDataCallback)(char*& buffer, unsigned& size); + + /// @} + /// @name Methods + /// @{ + public: + /// This function does the compression work. The block of memory starting + /// at \p in and extending for \p size bytes is compressed. The compressed + /// output is written to memory blocks returned by the \p cb callback. The + /// caller must provide an implementation of the OutputDataCallback + /// function type and provide its address as \p cb. Note that the callback + /// function will be called as many times as necessary to complete the + /// compression of the \p in block but that the total size will generally + /// be less than \p size. It is a good idea to provide as large a value to + /// the callback's \p size parameter as possible so that fewer calls to + /// the callback are made. The \p hint parameter tells the function which + /// kind of compression to start with. However, if its not available on + /// the platform, the algorithm "falls back" from bzip2 -> zlib -> simple. + /// @throws std::string if an error occurs + /// @returns the total size of the compressed data + /// @brief Compress a block of memory. + static uint64_t compress(char* in, unsigned size, OutputDataCallback* cb, + Algorithm hint = COMP_TYPE_BZIP2); + + /// This function does the decompression work. The block of memory + /// starting at \p in and extending for \p size bytes is decompressed. The + /// decompressed output is written to memory blocks returned by the \p cb + /// callback. The caller must provide an implementation of the + /// OutputDataCallback function type and provide its address as \p cb. + /// Note that the callback function will be called as many times as + /// necessary to complete the compression of the \p in block but that the + /// total size will generally be greater than \p size. It is a good idea + /// to provide as large a value to the callback's \p size parameter as + /// possible so that fewer calls to the callback are made. + /// @throws std::string if an error occurs + /// @returns the total size of the decompressed data + /// @brief Decompress a block of memory. + static uint64_t decompress(char *in, unsigned size, + OutputDataCallback* cb); + + /// @} + }; + } + + // vim: sw=2 ai + + #endif From reid at x10sys.com Mon Oct 4 05:49:52 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 05:49:52 -0500 Subject: [llvm-commits] CVS: llvm/lib/Support/Compressor.cpp Message-ID: <200410041049.FAA31505@zion.cs.uiuc.edu> Changes in directory llvm/lib/Support: Compressor.cpp added (r1.1) --- Log message: First version of a support utility to provide generalized compression in LLVM that handles availability and unavailability of bzip2 and zlib. --- Diffs of the changes: (+526 -0) Index: llvm/lib/Support/Compressor.cpp diff -c /dev/null llvm/lib/Support/Compressor.cpp:1.1 *** /dev/null Mon Oct 4 05:49:51 2004 --- llvm/lib/Support/Compressor.cpp Mon Oct 4 05:49:41 2004 *************** *** 0 **** --- 1,526 ---- + //===- lib/Support/Compressor.cpp -------------------------------*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Reid Spencer and is distributed under the + // University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file implements the llvm::Compressor class, an abstraction for memory + // block compression. + // + //===----------------------------------------------------------------------===// + + #include "llvm/Config/config.h" + #include "llvm/Support/Compressor.h" + #include "llvm/ADT/StringExtras.h" + #include + #include + + #ifdef HAVE_BZIP2 + #include + #endif + + #ifdef HAVE_ZLIB + #include + #endif + + #ifndef HAVE_BZIP2 + # ifndef HAVE_ZLIB + # warning No compression library is available!! + # endif + #endif + + namespace { + + inline int getdata(char*& buffer, unsigned& size, + llvm::Compressor::OutputDataCallback* cb) { + buffer = 0; + size = 0; + int result = (*cb)(buffer, size); + assert(buffer != 0 && "Invalid result from Compressor callback"); + assert(size != 0 && "Invalid result from Compressor callback"); + return result; + } + + //===----------------------------------------------------------------------===// + //=== RLCOMP - very simple run length compression scheme + //=== The code below transforms the input into blocks that are either + //=== compressed or not. Each block starts with a header byte that provides + //=== the length of the block. Values < 128 are uncompressed, values >128 + //=== are compressed. The value 128 is illegal. Currently, the algorithm is + //=== not completed and is #if'd out. + //===----------------------------------------------------------------------===// + + enum { + MAX_RLCOMP_OUT = 32768 + }; + + struct RLCOMP_stream { + // User provided fields + char* next_in; + unsigned avail_in; + char* next_out; + unsigned avail_out; + + // Information fields + uint64_t output_count; // Total count of output bytes + + #if 0 + // Algorithm fields + unsigned block_len; // Length of current block + unsigned compression; // State of compression 0=no, 1=yes, 2=indeterminate + char buffer[128]; // compression buffer (not used for decompress) + unsigned buflen; // bytes in compression buffer + bool pending; // is data pending to be written + char pending_data; // the pending data + unsigned clen; // length of the compressed block + #endif + }; + + void RLCOMP_init(RLCOMP_stream* s) { + s->output_count = 0; + #if 0 + s->block_len = 0; + s->compression = 2; + s->buflen = 0; + s->pending = false; + s->pending_data = 0; + s->clen = 0; + #endif + } + + inline bool RLCOMP_getchar(RLCOMP_stream* s, unsigned& data) { + #if 0 + if (s->avail_in) { + data = *s->next_in++; + s->avail_in--; + return true; + } + #endif + return false; + } + + inline bool RLCOMP_putchar(RLCOMP_stream* s, unsigned data) { + #if 0 + if (s->avail_out) { + *s->next_out++ = data; + s->avail_out--; + s->output_count++; + return true; + } else { + s->pending = true; + s->pending_data = data; + return false; + } + #else + return false; + #endif + } + + bool RLCOMP_compress(RLCOMP_stream* s) { + assert(s && "Invalid RLCOMP_stream"); + assert(s->next_in != 0); + assert(s->next_out != 0); + assert(s->avail_in >= 1); + assert(s->avail_out >= 1); + + #if 0 + + // Handle pending data from the last time in + if (s->pending) { + RLCOMP_putchar(s,s->pending_data); + s->pending = false; + } + + unsigned c = 0; + unsigned lastc = 0; + // Handle the degenerate len=1 case + if (!RLCOMP_getchar(s,lastc)) { + RLCOMP_putchar(s,1); + return RLCOMP_putchar(s,lastc); + } + + while (RLCOMP_getchar(s,c)) { + switch(s->compression) { + case 0: + if (lastc == c) { + s->compression = 1; + s->clen = 2 ; + } else { + if (!RLCOMP_putchar(s, c)) + return false; + } + break; + + case 1: + if (lastc != c) { + s->compression = 2; + if (!RLCOMP_putchar(s, s->clen)) + return false; + } else { + s->clen++; + } + break; + + case 2: + break; + } + lastc = c; + } + #endif + if (s->avail_out >= s->avail_in) { + ::memcpy(s->next_out, s->next_in, s->avail_in); + s->output_count += s->avail_in; + s->avail_out -= s->avail_in; + s->next_in += s->avail_in; + s->avail_in = 0; + return true; + } else { + ::memcpy(s->next_out, s->next_in, s->avail_out); + s->output_count += s->avail_out; + s->avail_in -= s->avail_out; + s->next_in += s->avail_out; + s->avail_out = 0; + return false; + } + } + + bool RLCOMP_decompress(RLCOMP_stream* s) { + assert(s && "Invalid RLCOMP_stream"); + assert(s->next_in != 0); + assert(s->next_out != 0); + assert(s->avail_in >= 1); + assert(s->avail_out >= 1); + + #if 0 + unsigned c = 0; + while (RLCOMP_getchar(s,c)) { + switch(s->compression) { + case 0: // This is not a compressed block + s->block_len--; + if (!RLCOMP_putchar(s,c)) + return false; + break; + + case 1: // This is a comperssed block + while (s->block_len-- > 0) + if (!RLCOMP_putchar(s,c)) + return false; + break; + + case 2: // This is the length field + if (c < 128) { + s->compression = 0; + s->block_len = c; + } else { + s->compression = 1; + s->block_len = c - 128; + } + continue; + + default: // oops! + throw std::string("Invalid compression state"); + } + if (s->block_len <= 0) + s->compression = 2; + } + + if (s->repeat > 0) + throw std::string("Invalid compression state"); + #endif + if (s->avail_out >= s->avail_in) { + ::memcpy(s->next_out, s->next_in, s->avail_in); + s->output_count += s->avail_in; + s->avail_out -= s->avail_in; + s->next_in += s->avail_in; + s->avail_in = 0; + return true; + } else { + ::memcpy(s->next_out, s->next_in, s->avail_out); + s->output_count += s->avail_out; + s->avail_in -= s->avail_out; + s->next_in += s->avail_out; + s->avail_out = 0; + return false; + } + } + + void RLCOMP_end(RLCOMP_stream* strm) { + } + + } + + namespace llvm { + + // Compress in one of three ways + uint64_t Compressor::compress(char* in, unsigned size, + OutputDataCallback* cb, Algorithm hint) { + assert(in && "Can't compress null buffer"); + assert(size && "Can't compress empty buffer"); + assert(cb && "Can't compress without a callback function"); + + uint64_t result = 0; + + switch (hint) { + case COMP_TYPE_BZIP2: { + #if defined(HAVE_BZIP2) + // Set up the bz_stream + bz_stream bzdata; + bzdata.bzalloc = 0; + bzdata.bzfree = 0; + bzdata.opaque = 0; + bzdata.next_in = in; + bzdata.avail_in = size; + bzdata.next_out = 0; + bzdata.avail_out = 0; + switch ( BZ2_bzCompressInit(&bzdata, 9, 0, 0) ) { + case BZ_CONFIG_ERROR: throw std::string("bzip2 library mis-compiled"); + case BZ_PARAM_ERROR: throw std::string("Compressor internal error"); + case BZ_MEM_ERROR: throw std::string("Out of memory"); + case BZ_OK: + default: + break; + } + + // Get a block of memory + if (0 != getdata(bzdata.next_out, bzdata.avail_out,cb)) { + BZ2_bzCompressEnd(&bzdata); + throw std::string("Can't allocate output buffer"); + } + + // Put compression code in first byte + (*bzdata.next_out++) = COMP_TYPE_BZIP2; + bzdata.avail_out--; + + // Compress it + int bzerr = BZ_FINISH_OK; + while (BZ_FINISH_OK == (bzerr = BZ2_bzCompress(&bzdata, BZ_FINISH))) { + if (0 != getdata(bzdata.next_out, bzdata.avail_out,cb)) { + BZ2_bzCompressEnd(&bzdata); + throw std::string("Can't allocate output buffer"); + } + } + switch (bzerr) { + case BZ_SEQUENCE_ERROR: + case BZ_PARAM_ERROR: throw std::string("Param/Sequence error"); + case BZ_FINISH_OK: + case BZ_STREAM_END: break; + default: throw std::string("Oops: ") + utostr(unsigned(bzerr)); + } + + // Finish + result = (static_cast(bzdata.total_out_hi32) << 32) | + bzdata.total_out_lo32 + 1; + + BZ2_bzCompressEnd(&bzdata); + break; + #else + // FALL THROUGH + #endif + } + + case COMP_TYPE_ZLIB: { + #if defined(HAVE_ZLIB) + z_stream zdata; + zdata.zalloc = Z_NULL; + zdata.zfree = Z_NULL; + zdata.opaque = Z_NULL; + zdata.next_in = reinterpret_cast(in); + zdata.avail_in = size; + if (Z_OK != deflateInit(&zdata,Z_BEST_COMPRESSION)) + throw std::string(zdata.msg ? zdata.msg : "zlib error"); + + if (0 != getdata((char*&)(zdata.next_out), zdata.avail_out,cb)) { + deflateEnd(&zdata); + throw std::string("Can't allocate output buffer"); + } + + (*zdata.next_out++) = COMP_TYPE_ZLIB; + zdata.avail_out--; + + int flush = 0; + while ( Z_OK == deflate(&zdata,0) && zdata.avail_out == 0) { + if (0 != getdata((char*&)zdata.next_out, zdata.avail_out, cb)) { + deflateEnd(&zdata); + throw std::string("Can't allocate output buffer"); + } + } + + while ( Z_STREAM_END != deflate(&zdata, Z_FINISH)) { + if (0 != getdata((char*&)zdata.next_out, zdata.avail_out, cb)) { + deflateEnd(&zdata); + throw std::string("Can't allocate output buffer"); + } + } + + result = static_cast(zdata.total_out) + 1; + deflateEnd(&zdata); + break; + + #else + // FALL THROUGH + #endif + } + + case COMP_TYPE_SIMPLE: { + RLCOMP_stream sdata; + sdata.next_in = in; + sdata.avail_in = size; + RLCOMP_init(&sdata); + + if (0 != getdata(sdata.next_out, sdata.avail_out,cb)) { + throw std::string("Can't allocate output buffer"); + } + + *(sdata.next_out++) = COMP_TYPE_SIMPLE; + sdata.avail_out--; + + while (!RLCOMP_compress(&sdata)) { + if (0 != getdata(sdata.next_out, sdata.avail_out,cb)) { + throw std::string("Can't allocate output buffer"); + } + } + + result = sdata.output_count + 1; + RLCOMP_end(&sdata); + break; + } + default: + throw std::string("Invalid compression type hint"); + } + return result; + } + + // Decompress in one of three ways + uint64_t Compressor::decompress(char *in, unsigned size, + OutputDataCallback* cb) { + assert(in && "Can't decompress null buffer"); + assert(size > 1 && "Can't decompress empty buffer"); + assert(cb && "Can't decompress without a callback function"); + + uint64_t result = 0; + + switch (*in++) { + case COMP_TYPE_BZIP2: { + #if !defined(HAVE_BZIP2) + throw std::string("Can't decompress BZIP2 data"); + #else + // Set up the bz_stream + bz_stream bzdata; + bzdata.bzalloc = 0; + bzdata.bzfree = 0; + bzdata.opaque = 0; + bzdata.next_in = in; + bzdata.avail_in = size - 1; + bzdata.next_out = 0; + bzdata.avail_out = 0; + switch ( BZ2_bzDecompressInit(&bzdata, 0, 0) ) { + case BZ_CONFIG_ERROR: throw std::string("bzip2 library mis-compiled"); + case BZ_PARAM_ERROR: throw std::string("Compressor internal error"); + case BZ_MEM_ERROR: throw std::string("Out of memory"); + case BZ_OK: + default: + break; + } + + // Get a block of memory + if (0 != getdata(bzdata.next_out, bzdata.avail_out,cb)) { + BZ2_bzDecompressEnd(&bzdata); + throw std::string("Can't allocate output buffer"); + } + + // Decompress it + int bzerr = BZ_OK; + while (BZ_OK == (bzerr = BZ2_bzDecompress(&bzdata))) { + if (0 != getdata(bzdata.next_out, bzdata.avail_out,cb)) { + BZ2_bzDecompressEnd(&bzdata); + throw std::string("Can't allocate output buffer"); + } + } + + switch (bzerr) { + case BZ_PARAM_ERROR: throw std::string("Compressor internal error"); + case BZ_MEM_ERROR: throw std::string("Out of memory"); + case BZ_DATA_ERROR: throw std::string("Data integrity error"); + case BZ_DATA_ERROR_MAGIC:throw std::string("Data is not BZIP2"); + default: throw("Ooops"); + case BZ_STREAM_END: + break; + } + + // Finish + result = (static_cast(bzdata.total_out_hi32) << 32) | + bzdata.total_out_lo32; + BZ2_bzDecompressEnd(&bzdata); + break; + } + #endif + + case COMP_TYPE_ZLIB: { + #if !defined(HAVE_ZLIB) + throw std::string("Can't decompress ZLIB data"); + #else + z_stream zdata; + zdata.zalloc = Z_NULL; + zdata.zfree = Z_NULL; + zdata.opaque = Z_NULL; + zdata.next_in = reinterpret_cast(in); + zdata.avail_in = size - 1; + if ( Z_OK != inflateInit(&zdata)) + throw std::string(zdata.msg ? zdata.msg : "zlib error"); + + if (0 != getdata((char*&)zdata.next_out, zdata.avail_out,cb)) { + inflateEnd(&zdata); + throw std::string("Can't allocate output buffer"); + } + + int zerr = Z_OK; + while (Z_OK == (zerr = inflate(&zdata,0))) { + if (0 != getdata((char*&)zdata.next_out, zdata.avail_out,cb)) { + inflateEnd(&zdata); + throw std::string("Can't allocate output buffer"); + } + } + + if (zerr != Z_STREAM_END) + throw std::string(zdata.msg?zdata.msg:"zlib error"); + + result = static_cast(zdata.total_out); + inflateEnd(&zdata); + break; + #endif + } + + case COMP_TYPE_SIMPLE: { + RLCOMP_stream sdata; + sdata.next_in = in; + sdata.avail_in = size - 1; + RLCOMP_init(&sdata); + + if (0 != getdata(sdata.next_out, sdata.avail_out,cb)) { + throw std::string("Can't allocate output buffer"); + } + + while (!RLCOMP_decompress(&sdata)) { + if (0 != getdata(sdata.next_out, sdata.avail_out,cb)) { + throw std::string("Can't allocate output buffer"); + } + } + + result = sdata.output_count; + RLCOMP_end(&sdata); + break; + } + + default: + throw std::string("Unknown type of compressed data"); + } + + return result; + } + + } + + // vim: sw=2 ai From reid at x10sys.com Mon Oct 4 06:08:44 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 06:08:44 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/FreeBSD/MappedFile.cpp Message-ID: <200410041108.GAA01108@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/FreeBSD: MappedFile.cpp added (r1.1) --- Log message: First version of the MappedFile abstraction for operating system idependent mapping of files. This first version uses mmap where its available. The class needs to implement an alternate mechanism based on malloc'd memory and file reading/writing for platforms without virtual memory. --- Diffs of the changes: (+18 -0) Index: llvm/lib/System/FreeBSD/MappedFile.cpp diff -c /dev/null llvm/lib/System/FreeBSD/MappedFile.cpp:1.1 *** /dev/null Mon Oct 4 06:08:42 2004 --- llvm/lib/System/FreeBSD/MappedFile.cpp Mon Oct 4 06:08:32 2004 *************** *** 0 **** --- 1,18 ---- + //===- FreeBSD/MappedFile.cpp - FreeBSD MappedFile Impl. --------*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Reid Spencer and is distributed under the + // University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file provides the FreeBSD specific implementation of the MappedFile + // concept. + // + //===----------------------------------------------------------------------===// + + // Include the generic unix implementation + #include "../Unix/MappedFile.cpp" + + // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab From reid at x10sys.com Mon Oct 4 06:08:44 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 06:08:44 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/Darwin/MappedFile.cpp Message-ID: <200410041108.GAA01107@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/Darwin: MappedFile.cpp added (r1.1) --- Log message: First version of the MappedFile abstraction for operating system idependent mapping of files. This first version uses mmap where its available. The class needs to implement an alternate mechanism based on malloc'd memory and file reading/writing for platforms without virtual memory. --- Diffs of the changes: (+18 -0) Index: llvm/lib/System/Darwin/MappedFile.cpp diff -c /dev/null llvm/lib/System/Darwin/MappedFile.cpp:1.1 *** /dev/null Mon Oct 4 06:08:42 2004 --- llvm/lib/System/Darwin/MappedFile.cpp Mon Oct 4 06:08:32 2004 *************** *** 0 **** --- 1,18 ---- + //===- Darwin/MappedFile.cpp - Darwin MappedFile Implementation -*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Reid Spencer and is distributed under the + // University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file provides the Darwin specific implementation of the MappedFile + // concept. + // + //===----------------------------------------------------------------------===// + + // Include the generic unix implementation + #include "../Unix/MappedFile.cpp" + + // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab From reid at x10sys.com Mon Oct 4 06:08:44 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 06:08:44 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/MappedFile.cpp Message-ID: <200410041108.GAA01106@zion.cs.uiuc.edu> Changes in directory llvm/lib/System: MappedFile.cpp added (r1.1) --- Log message: First version of the MappedFile abstraction for operating system idependent mapping of files. This first version uses mmap where its available. The class needs to implement an alternate mechanism based on malloc'd memory and file reading/writing for platforms without virtual memory. --- Diffs of the changes: (+29 -0) Index: llvm/lib/System/MappedFile.cpp diff -c /dev/null llvm/lib/System/MappedFile.cpp:1.1 *** /dev/null Mon Oct 4 06:08:42 2004 --- llvm/lib/System/MappedFile.cpp Mon Oct 4 06:08:32 2004 *************** *** 0 **** --- 1,29 ---- + //===- MappedFile.cpp - MappedFile Support ----------------------*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Reid Spencer and is distributed under the + // University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file implements the mapped file concept. + // + //===----------------------------------------------------------------------===// + + #include "llvm/System/MappedFile.h" + + namespace llvm { + using namespace sys; + + //===----------------------------------------------------------------------===// + //=== WARNING: Implementation here must contain only TRULY operating system + //=== independent code. + //===----------------------------------------------------------------------===// + + } + + // Include the platform-specific parts of this class. + #include "platform/MappedFile.cpp" + + // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab From reid at x10sys.com Mon Oct 4 06:08:44 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 06:08:44 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/System/MappedFile.h Message-ID: <200410041108.GAA01117@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/System: MappedFile.h added (r1.1) --- Log message: First version of the MappedFile abstraction for operating system idependent mapping of files. This first version uses mmap where its available. The class needs to implement an alternate mechanism based on malloc'd memory and file reading/writing for platforms without virtual memory. --- Diffs of the changes: (+160 -0) Index: llvm/include/llvm/System/MappedFile.h diff -c /dev/null llvm/include/llvm/System/MappedFile.h:1.1 *** /dev/null Mon Oct 4 06:08:42 2004 --- llvm/include/llvm/System/MappedFile.h Mon Oct 4 06:08:32 2004 *************** *** 0 **** --- 1,160 ---- + //===- llvm/System/MappedFile.h - MappedFile OS Concept ---------*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Reid Spencer and is distributed under the + // University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file declares the llvm::sys::MappedFile class. + // + //===----------------------------------------------------------------------===// + + #ifndef LLVM_SYSTEM_MAPPEDFILE_H + #define LLVM_SYSTEM_MAPPEDFILE_H + + #include "llvm/System/Path.h" + + namespace llvm { + namespace sys { + + /// Forward declare a class used for holding platform specific information + /// that needs to be + class MappedFileInfo; + + /// This class provides an abstraction for a memory mapped file in the + /// operating system's filesystem. It provides platform independent operations + /// for mapping a file into memory for both read and write access. This class + /// does not provide facilities for finding the file or operating on paths to + /// files. The sys::Path class is used for that. + /// @since 1.4 + /// @brief An abstraction for memory mapped files. + class MappedFile { + /// @name Types + /// @{ + public: + enum MappingOptions { + READ_ACCESS = 0x0001, ///< Map the file for reading + WRITE_ACCESS = 0x0002, ///< Map the file for write access + EXEC_ACCESS = 0x0004, ///< Map the file for execution access + SHARED_MAPPING = 0x0008, ///< Map the file shared with other processes + }; + /// @} + /// @name Constructors + /// @{ + public: + /// Construct a MappedFile to the \p path in the operating system's file + /// system with the mapping \p options provided. + /// @throws std::string if an error occurs + MappedFile(const Path& path, int options = READ_ACCESS) + : path_(path), options_(options), base_(0), info_(0) { + initialize(); + } + + /// Destruct a MappedFile and release all memory associated with it. + /// @throws std::string if an error occurs + ~MappedFile() { + terminate(); + path_.clear(); + } + + /// @} + /// @name Accessors + /// @{ + public: + /// This function determines if the file is currently mapped or not. + /// @returns true iff the file is mapped into memory, false otherwise + /// @brief Determine if a MappedFile is currently mapped + /// @throws nothing + bool isMapped() const { return base_ != 0; } + + /// This function returns a void* pointer to the base address of the file + /// mapping. This is the memory address of the first byte in the file. + /// Note that although a non-const pointer is returned, the memory might + /// not actually be writable, depending on the MappingOptions used when + /// the MappedFile was opened. + /// @returns The base pointer to the memory mapped file. + /// @brief Obtain the base pointer to the memory mapped file. + /// @throws nothing + void* base() const { return base_; } + + /// This function returns a char* pointer to the base address of the file + /// mapping. This is the memory address of the first byte in the file. + /// Note that although a non-const pointer is returned, the memory might + /// not actually be writable, depending on the MappingOptions used when + /// the MappedFile was opened. + /// @returns The base pointer to the memory mapped file as a char pointer. + /// @brief Obtain the base pointer to the memory mapped file. + /// @throws nothing + char* charBase() const { return reinterpret_cast(base_); } + + /// This function returns a reference to the sys::Path object kept by the + /// MappedFile object. This contains the path to the file that is or + /// will be mapped. + /// @returns sys::Path containing the path name. + /// @brief Returns the mapped file's path as a sys::Path + /// @throws nothing + const sys::Path& path() const { return path_; } + + /// This function returns the number of bytes in the file. + /// @throws std::string if an error occurs + size_t size(); + + /// @} + /// @name Mutators + /// @{ + public: + /// The mapped file is removed from memory. If the file was mapped for + /// write access, the memory contents will be automatically synchronized + /// with the file's disk contents. + /// @brief Remove the file mapping from memory. + void unmap(); + + /// The mapped file is put into memory. + /// @returns The base memory address of the mapped file. + /// @brief Map the file into memory. + void* map(); + + /// This method causes the size of the file, and consequently the size + /// of the mapping to be set. This is logically the same as unmap(), + /// adjust size of the file, map(). Consequently, when calling this + /// function, the caller should not rely on previous results of the + /// map(), base(), or baseChar() members as they may point to invalid + /// areas of memory after this call. + /// @throws std::string if an error occurs + /// @brief Set a full path from a std::string + void size(size_t new_size); + + /// @} + /// @name Implementation + /// @{ + private: + void initialize(); ///< Initialize platform-specific portion + void terminate(); ///< Terminate platform-specific portion + + /// @} + /// @name Data + /// @{ + private: + sys::Path path_; ///< Path to the file. + int options_; ///< Options used to create the mapping + void* base_; ///< Pointer to the base memory address + MappedFileInfo* info_; ///< Platform specific info for the mapping + + /// @} + /// @name Deprecated + /// @{ + private: + ///< Disallow assignment + MappedFile& operator = ( const MappedFile & that ); + ///< Disallow copying + MappedFile(const MappedFile& that); + /// @} + }; + } + } + + // vim: sw=2 + + #endif From reid at x10sys.com Mon Oct 4 06:08:45 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 06:08:45 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/Unix/MappedFile.cpp Message-ID: <200410041108.GAA01124@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/Unix: MappedFile.cpp added (r1.1) --- Log message: First version of the MappedFile abstraction for operating system idependent mapping of files. This first version uses mmap where its available. The class needs to implement an alternate mechanism based on malloc'd memory and file reading/writing for platforms without virtual memory. --- Diffs of the changes: (+138 -0) Index: llvm/lib/System/Unix/MappedFile.cpp diff -c /dev/null llvm/lib/System/Unix/MappedFile.cpp:1.1 *** /dev/null Mon Oct 4 06:08:42 2004 --- llvm/lib/System/Unix/MappedFile.cpp Mon Oct 4 06:08:32 2004 *************** *** 0 **** --- 1,138 ---- + //===- Unix/MappedFile.cpp - Unix MappedFile Implementation -----*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Reid Spencer and is distributed under the + // University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file provides the generic Unix implementation of the MappedFile concept. + // + //===----------------------------------------------------------------------===// + + //===----------------------------------------------------------------------===// + //=== WARNING: Implementation here must contain only generic UNIX code that + //=== is guaranteed to work on *all* UNIX variants. + //===----------------------------------------------------------------------===// + + #include "llvm/System/Process.h" + #include "Unix.h" + #include + #include + + namespace llvm { + using namespace sys; + + struct sys::MappedFileInfo { + int fd_; + struct stat sbuf_; + }; + + void MappedFile::initialize() { + if (path_.exists()) { + info_ = new MappedFileInfo; + int mode = 0; + if (options_&READ_ACCESS) + if (options_&WRITE_ACCESS) + mode = O_RDWR; + else + mode = O_RDONLY; + else if (options_&WRITE_ACCESS) + mode = O_WRONLY; + info_->fd_ = ::open(path_.c_str(),mode); + if (info_->fd_ < 0) { + delete info_; + info_ = 0; + ThrowErrno(std::string("Can't open file: ") + path_.get()); + } + struct stat sbuf; + if(::fstat(info_->fd_, &info_->sbuf_) < 0) { + ::close(info_->fd_); + delete info_; + info_ = 0; + ThrowErrno(std::string("Can't stat file: ") + path_.get()); + } + } + } + + void MappedFile::terminate() { + assert(info_ && "MappedFile not initialized"); + if (info_->fd_ >= 0) + ::close(info_->fd_); + delete info_; + info_ = 0; + } + + void MappedFile::unmap() { + assert(info_ && "MappedFile not initialized"); + if (isMapped()) { + if (options_ & WRITE_ACCESS) + ::msync(base_, info_->sbuf_.st_size, MS_SYNC); + ::munmap(base_, info_->sbuf_.st_size); + } + } + + void* MappedFile::map() { + if (!isMapped()) { + int prot = PROT_NONE; + int flags = MAP_FILE; + if (options_ == 0) { + prot = PROT_READ; + flags = MAP_PRIVATE; + } else { + if (options_ & READ_ACCESS) + prot |= PROT_READ; + if (options_ & WRITE_ACCESS) + prot |= PROT_WRITE; + if (options_ & EXEC_ACCESS) + prot |= PROT_EXEC; + if (options_ & SHARED_MAPPING) + flags |= MAP_SHARED; + else + flags |= MAP_PRIVATE; + } + size_t map_size = ((info_->sbuf_.st_size / Process::GetPageSize())+1) * + Process::GetPageSize(); + + base_ = ::mmap(0, map_size, prot, flags, info_->fd_, 0); + if (base_ == MAP_FAILED) + ThrowErrno(std::string("Can't map file:") + path_.get()); + } + return base_; + } + + size_t MappedFile::size() { + assert(info_ && "MappedFile not initialized"); + return info_->sbuf_.st_size; + } + + void MappedFile::size(size_t new_size) { + assert(info_ && "MappedFile not initialized"); + + // Take the mapping out of memory + this->unmap(); + + // Adjust the current size to a page boundary + size_t cur_size = ((info_->sbuf_.st_size / Process::GetPageSize())+1) * + Process::GetPageSize(); + + // Adjust the new_size to a page boundary + new_size = ((new_size / Process::GetPageSize())+1) * + Process::GetPageSize(); + + // If the file needs to be extended + if (new_size > cur_size) { + // Ensure we can allocate at least the idodes necessary to handle the + // file size requested. + ::lseek(info_->fd_, new_size, SEEK_SET); + ::write(info_->fd_, "\0", 1); + } + + // Seek to current end of file. + this->map(); + } + + } + + // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab From reid at x10sys.com Mon Oct 4 06:08:45 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 06:08:45 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/SunOS/MappedFile.cpp Message-ID: <200410041108.GAA01118@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/SunOS: MappedFile.cpp added (r1.1) --- Log message: First version of the MappedFile abstraction for operating system idependent mapping of files. This first version uses mmap where its available. The class needs to implement an alternate mechanism based on malloc'd memory and file reading/writing for platforms without virtual memory. --- Diffs of the changes: (+18 -0) Index: llvm/lib/System/SunOS/MappedFile.cpp diff -c /dev/null llvm/lib/System/SunOS/MappedFile.cpp:1.1 *** /dev/null Mon Oct 4 06:08:42 2004 --- llvm/lib/System/SunOS/MappedFile.cpp Mon Oct 4 06:08:32 2004 *************** *** 0 **** --- 1,18 ---- + //===- SunOS/MappedFile.cpp - SunOS MappedFile Implementation ---*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Reid Spencer and is distributed under the + // University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file provides the SunOS specific implementation of the MappedFile + // concept. + // + //===----------------------------------------------------------------------===// + + // Include the generic unix implementation + #include "../Unix/MappedFile.cpp" + + // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab From reid at x10sys.com Mon Oct 4 06:08:45 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 06:08:45 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/Linux/MappedFile.cpp Message-ID: <200410041108.GAA01121@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/Linux: MappedFile.cpp added (r1.1) --- Log message: First version of the MappedFile abstraction for operating system idependent mapping of files. This first version uses mmap where its available. The class needs to implement an alternate mechanism based on malloc'd memory and file reading/writing for platforms without virtual memory. --- Diffs of the changes: (+18 -0) Index: llvm/lib/System/Linux/MappedFile.cpp diff -c /dev/null llvm/lib/System/Linux/MappedFile.cpp:1.1 *** /dev/null Mon Oct 4 06:08:42 2004 --- llvm/lib/System/Linux/MappedFile.cpp Mon Oct 4 06:08:32 2004 *************** *** 0 **** --- 1,18 ---- + //===- Linux/MappedFile.cpp - Linux MappedFile Implementation ---*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Reid Spencer and is distributed under the + // University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file provides the Linux specific implementation of the MappedFile + // concept. + // + //===----------------------------------------------------------------------===// + + // Include the generic unix implementation + #include "../Unix/MappedFile.cpp" + + // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab From reid at x10sys.com Mon Oct 4 06:08:45 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 06:08:45 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/Interix/MappedFile.cpp Message-ID: <200410041108.GAA01119@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/Interix: MappedFile.cpp added (r1.1) --- Log message: First version of the MappedFile abstraction for operating system idependent mapping of files. This first version uses mmap where its available. The class needs to implement an alternate mechanism based on malloc'd memory and file reading/writing for platforms without virtual memory. --- Diffs of the changes: (+18 -0) Index: llvm/lib/System/Interix/MappedFile.cpp diff -c /dev/null llvm/lib/System/Interix/MappedFile.cpp:1.1 *** /dev/null Mon Oct 4 06:08:42 2004 --- llvm/lib/System/Interix/MappedFile.cpp Mon Oct 4 06:08:32 2004 *************** *** 0 **** --- 1,18 ---- + //===- Interix/MappedFile.cpp - Interix MappedFile Impl. --------*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Reid Spencer and is distributed under the + // University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file provides the Interix specific implementation of the MappedFile + // concept. + // + //===----------------------------------------------------------------------===// + + // Include the generic unix implementation + #include "../Unix/MappedFile.cpp" + + // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab From reid at x10sys.com Mon Oct 4 06:08:45 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 06:08:45 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/Cygwin/MappedFile.cpp Message-ID: <200410041108.GAA01123@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/Cygwin: MappedFile.cpp added (r1.1) --- Log message: First version of the MappedFile abstraction for operating system idependent mapping of files. This first version uses mmap where its available. The class needs to implement an alternate mechanism based on malloc'd memory and file reading/writing for platforms without virtual memory. --- Diffs of the changes: (+18 -0) Index: llvm/lib/System/Cygwin/MappedFile.cpp diff -c /dev/null llvm/lib/System/Cygwin/MappedFile.cpp:1.1 *** /dev/null Mon Oct 4 06:08:42 2004 --- llvm/lib/System/Cygwin/MappedFile.cpp Mon Oct 4 06:08:32 2004 *************** *** 0 **** --- 1,18 ---- + //===- Cygwin/MappedFile.cpp - Cygwin MappedFile Implementation -*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Reid Spencer and is distributed under the + // University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file provides the Cygwin specific implementation of the MappedFile + // concept. + // + //===----------------------------------------------------------------------===// + + // Include the generic unix implementation + #include "../Unix/MappedFile.cpp" + + // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab From reid at x10sys.com Mon Oct 4 06:08:44 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 06:08:44 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/AIX/MappedFile.cpp Message-ID: <200410041108.GAA01116@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/AIX: MappedFile.cpp added (r1.1) --- Log message: First version of the MappedFile abstraction for operating system idependent mapping of files. This first version uses mmap where its available. The class needs to implement an alternate mechanism based on malloc'd memory and file reading/writing for platforms without virtual memory. --- Diffs of the changes: (+17 -0) Index: llvm/lib/System/AIX/MappedFile.cpp diff -c /dev/null llvm/lib/System/AIX/MappedFile.cpp:1.1 *** /dev/null Mon Oct 4 06:08:42 2004 --- llvm/lib/System/AIX/MappedFile.cpp Mon Oct 4 06:08:32 2004 *************** *** 0 **** --- 1,17 ---- + //===- AIX/MappedFile.cpp - AIX MappedFile Implementation --------*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Reid Spencer and is distributed under the + // University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file provides the AIX specific implementation of the MappedFile concept. + // + //===----------------------------------------------------------------------===// + + // Include the generic unix implementation + #include "../Unix/MappedFile.cpp" + + // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab From reid at x10sys.com Mon Oct 4 06:08:45 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 06:08:45 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/Win32/MappedFile.cpp Message-ID: <200410041108.GAA01120@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/Win32: MappedFile.cpp added (r1.1) --- Log message: First version of the MappedFile abstraction for operating system idependent mapping of files. This first version uses mmap where its available. The class needs to implement an alternate mechanism based on malloc'd memory and file reading/writing for platforms without virtual memory. --- Diffs of the changes: (+38 -0) Index: llvm/lib/System/Win32/MappedFile.cpp diff -c /dev/null llvm/lib/System/Win32/MappedFile.cpp:1.1 *** /dev/null Mon Oct 4 06:08:42 2004 --- llvm/lib/System/Win32/MappedFile.cpp Mon Oct 4 06:08:32 2004 *************** *** 0 **** --- 1,38 ---- + //===- Win32/MappedFile.cpp - Win32 MappedFile Implementation ---*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Reid Spencer and is distributed under the + // University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file provides the Win32 specific implementation of the MappedFile + // concept. + // + //===----------------------------------------------------------------------===// + + #include "Win32.h" + + void MappedFile::initialize() { + } + + void MappedFile::terminate() { + } + + void MappedFile::unmap() { + } + + void* MappedFile::map() { + static char junk[4096]; + return junk; + } + + size_t MappedFile::size() { + return 4096; + } + + void MappedFile::size(size_t new_size) { + } + + // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab From lattner at cs.uiuc.edu Mon Oct 4 11:33:38 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 11:33:38 -0500 Subject: [llvm-commits] CVS: llvm/lib/Support/Compressor.cpp Message-ID: <200410041633.LAA10579@apoc.cs.uiuc.edu> Changes in directory llvm/lib/Support: Compressor.cpp updated: 1.1 -> 1.2 --- Log message: Fix build if not HAVE_BZIP2 --- Diffs of the changes: (+1 -1) Index: llvm/lib/Support/Compressor.cpp diff -u llvm/lib/Support/Compressor.cpp:1.1 llvm/lib/Support/Compressor.cpp:1.2 --- llvm/lib/Support/Compressor.cpp:1.1 Mon Oct 4 05:49:41 2004 +++ llvm/lib/Support/Compressor.cpp Mon Oct 4 11:33:25 2004 @@ -455,8 +455,8 @@ bzdata.total_out_lo32; BZ2_bzDecompressEnd(&bzdata); break; - } #endif + } case COMP_TYPE_ZLIB: { #if !defined(HAVE_ZLIB) From reid at x10sys.com Mon Oct 4 12:26:37 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 12:26:37 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/System/MappedFile.h Message-ID: <200410041726.MAA11931@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/System: MappedFile.h updated: 1.1 -> 1.2 --- Log message: Minor corrections suggested by Chris' ever-watchful eye. --- Diffs of the changes: (+4 -9) Index: llvm/include/llvm/System/MappedFile.h diff -u llvm/include/llvm/System/MappedFile.h:1.1 llvm/include/llvm/System/MappedFile.h:1.2 --- llvm/include/llvm/System/MappedFile.h:1.1 Mon Oct 4 06:08:32 2004 +++ llvm/include/llvm/System/MappedFile.h Mon Oct 4 12:26:26 2004 @@ -48,16 +48,11 @@ /// system with the mapping \p options provided. /// @throws std::string if an error occurs MappedFile(const Path& path, int options = READ_ACCESS) - : path_(path), options_(options), base_(0), info_(0) { - initialize(); - } + : path_(path), options_(options), base_(0), info_(0) { initialize(); } /// Destruct a MappedFile and release all memory associated with it. /// @throws std::string if an error occurs - ~MappedFile() { - terminate(); - path_.clear(); - } + ~MappedFile() { terminate(); } /// @} /// @name Accessors @@ -123,7 +118,7 @@ /// map(), base(), or baseChar() members as they may point to invalid /// areas of memory after this call. /// @throws std::string if an error occurs - /// @brief Set a full path from a std::string + /// @brief Set the size of the file and memory mapping. void size(size_t new_size); /// @} @@ -143,7 +138,7 @@ MappedFileInfo* info_; ///< Platform specific info for the mapping /// @} - /// @name Deprecated + /// @name Disabled /// @{ private: ///< Disallow assignment From reid at x10sys.com Mon Oct 4 12:29:36 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 12:29:36 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/Support/Compressor.h Message-ID: <200410041729.MAA12013@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/Support: Compressor.h updated: 1.1 -> 1.2 --- Log message: Add a context for the callback so different compression scenarios can be distinguished. Tidy up documentation. Thanks, Chris. --- Diffs of the changes: (+11 -9) Index: llvm/include/llvm/Support/Compressor.h diff -u llvm/include/llvm/Support/Compressor.h:1.1 llvm/include/llvm/Support/Compressor.h:1.2 --- llvm/include/llvm/Support/Compressor.h:1.1 Mon Oct 4 05:49:41 2004 +++ llvm/include/llvm/Support/Compressor.h Mon Oct 4 12:29:25 2004 @@ -14,25 +14,25 @@ #ifndef LLVM_SUPPORT_COMPRESSOR_H #define LLVM_SUPPORT_COMPRESSOR_H -#include +#include "llvm/Support/DataTypes.h" namespace llvm { /// This class provides an abstraction for compressing a block of memory using /// a standard compression utility such as bzip2 or libz. This interface - /// allos us to abstraction the notion of compression and deal with alternate + /// allows us to abstract the notion of compression and deal with alternate /// compression scheme availability depending on the configured platform. This /// facility will always favor a bzip2 implementation if its available. - /// Otherwise, libz will be used if its available. If neither zlib nor bzip2 + /// Otherwise, libz will be used if it is available. If neither zlib nor bzip2 /// are available, a very simple algorithm provided by the Compressor class - /// will be used The type of compression used can be determined by inspecting + /// will be used. The type of compression used can be determined by inspecting /// the first byte of the compressed output. ASCII values '0', '1', and '2', /// denote the compression type as given in the Algorithm enumeration below. /// The Compressor is intended for use with memory mapped files where the /// entire data block to be compressed or decompressed is available in - /// memory. Output, however, can be gathered in repeated calls to a callback. + /// memory. However, output can be gathered in repeated calls to a callback. /// @since 1.4 - /// @brief An abstraction for memory to memory data compression + /// @brief An abstraction for memory to memory data (de)compression class Compressor { /// @name Types /// @{ @@ -50,7 +50,8 @@ /// @returns 0 for success, 1 for failure /// @throws nothing /// @brief Output callback function type - typedef unsigned (OutputDataCallback)(char*& buffer, unsigned& size); + typedef unsigned (OutputDataCallback)(char*& buffer, unsigned& size, + void* context); /// @} /// @name Methods @@ -72,7 +73,8 @@ /// @returns the total size of the compressed data /// @brief Compress a block of memory. static uint64_t compress(char* in, unsigned size, OutputDataCallback* cb, - Algorithm hint = COMP_TYPE_BZIP2); + Algorithm hint = COMP_TYPE_BZIP2, + void* context = 0); /// This function does the decompression work. The block of memory /// starting at \p in and extending for \p size bytes is decompressed. The @@ -88,7 +90,7 @@ /// @returns the total size of the decompressed data /// @brief Decompress a block of memory. static uint64_t decompress(char *in, unsigned size, - OutputDataCallback* cb); + OutputDataCallback* cb, void* context = 0); /// @} }; From reid at x10sys.com Mon Oct 4 12:29:36 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 12:29:36 -0500 Subject: [llvm-commits] CVS: llvm/lib/Support/Compressor.cpp Message-ID: <200410041729.MAA12009@zion.cs.uiuc.edu> Changes in directory llvm/lib/Support: Compressor.cpp updated: 1.2 -> 1.3 --- Log message: Add a context for the callback so different compression scenarios can be distinguished. Tidy up documentation. Thanks, Chris. --- Diffs of the changes: (+18 -18) Index: llvm/lib/Support/Compressor.cpp diff -u llvm/lib/Support/Compressor.cpp:1.2 llvm/lib/Support/Compressor.cpp:1.3 --- llvm/lib/Support/Compressor.cpp:1.2 Mon Oct 4 11:33:25 2004 +++ llvm/lib/Support/Compressor.cpp Mon Oct 4 12:29:25 2004 @@ -35,10 +35,10 @@ namespace { inline int getdata(char*& buffer, unsigned& size, - llvm::Compressor::OutputDataCallback* cb) { + llvm::Compressor::OutputDataCallback* cb, void* context) { buffer = 0; size = 0; - int result = (*cb)(buffer, size); + int result = (*cb)(buffer, size, context); assert(buffer != 0 && "Invalid result from Compressor callback"); assert(size != 0 && "Invalid result from Compressor callback"); return result; @@ -255,8 +255,8 @@ namespace llvm { // Compress in one of three ways -uint64_t Compressor::compress(char* in, unsigned size, - OutputDataCallback* cb, Algorithm hint) { +uint64_t Compressor::compress(char* in, unsigned size, OutputDataCallback* cb, + Algorithm hint, void* context ) { assert(in && "Can't compress null buffer"); assert(size && "Can't compress empty buffer"); assert(cb && "Can't compress without a callback function"); @@ -285,7 +285,7 @@ } // Get a block of memory - if (0 != getdata(bzdata.next_out, bzdata.avail_out,cb)) { + if (0 != getdata(bzdata.next_out, bzdata.avail_out,cb,context)) { BZ2_bzCompressEnd(&bzdata); throw std::string("Can't allocate output buffer"); } @@ -297,7 +297,7 @@ // Compress it int bzerr = BZ_FINISH_OK; while (BZ_FINISH_OK == (bzerr = BZ2_bzCompress(&bzdata, BZ_FINISH))) { - if (0 != getdata(bzdata.next_out, bzdata.avail_out,cb)) { + if (0 != getdata(bzdata.next_out, bzdata.avail_out,cb,context)) { BZ2_bzCompressEnd(&bzdata); throw std::string("Can't allocate output buffer"); } @@ -332,7 +332,7 @@ if (Z_OK != deflateInit(&zdata,Z_BEST_COMPRESSION)) throw std::string(zdata.msg ? zdata.msg : "zlib error"); - if (0 != getdata((char*&)(zdata.next_out), zdata.avail_out,cb)) { + if (0 != getdata((char*&)(zdata.next_out), zdata.avail_out,cb,context)) { deflateEnd(&zdata); throw std::string("Can't allocate output buffer"); } @@ -342,14 +342,14 @@ int flush = 0; while ( Z_OK == deflate(&zdata,0) && zdata.avail_out == 0) { - if (0 != getdata((char*&)zdata.next_out, zdata.avail_out, cb)) { + if (0 != getdata((char*&)zdata.next_out, zdata.avail_out, cb,context)) { deflateEnd(&zdata); throw std::string("Can't allocate output buffer"); } } while ( Z_STREAM_END != deflate(&zdata, Z_FINISH)) { - if (0 != getdata((char*&)zdata.next_out, zdata.avail_out, cb)) { + if (0 != getdata((char*&)zdata.next_out, zdata.avail_out, cb,context)) { deflateEnd(&zdata); throw std::string("Can't allocate output buffer"); } @@ -370,7 +370,7 @@ sdata.avail_in = size; RLCOMP_init(&sdata); - if (0 != getdata(sdata.next_out, sdata.avail_out,cb)) { + if (0 != getdata(sdata.next_out, sdata.avail_out,cb,context)) { throw std::string("Can't allocate output buffer"); } @@ -378,7 +378,7 @@ sdata.avail_out--; while (!RLCOMP_compress(&sdata)) { - if (0 != getdata(sdata.next_out, sdata.avail_out,cb)) { + if (0 != getdata(sdata.next_out, sdata.avail_out,cb,context)) { throw std::string("Can't allocate output buffer"); } } @@ -395,7 +395,7 @@ // Decompress in one of three ways uint64_t Compressor::decompress(char *in, unsigned size, - OutputDataCallback* cb) { + OutputDataCallback* cb, void* context) { assert(in && "Can't decompress null buffer"); assert(size > 1 && "Can't decompress empty buffer"); assert(cb && "Can't decompress without a callback function"); @@ -426,7 +426,7 @@ } // Get a block of memory - if (0 != getdata(bzdata.next_out, bzdata.avail_out,cb)) { + if (0 != getdata(bzdata.next_out, bzdata.avail_out,cb,context)) { BZ2_bzDecompressEnd(&bzdata); throw std::string("Can't allocate output buffer"); } @@ -434,7 +434,7 @@ // Decompress it int bzerr = BZ_OK; while (BZ_OK == (bzerr = BZ2_bzDecompress(&bzdata))) { - if (0 != getdata(bzdata.next_out, bzdata.avail_out,cb)) { + if (0 != getdata(bzdata.next_out, bzdata.avail_out,cb,context)) { BZ2_bzDecompressEnd(&bzdata); throw std::string("Can't allocate output buffer"); } @@ -471,14 +471,14 @@ if ( Z_OK != inflateInit(&zdata)) throw std::string(zdata.msg ? zdata.msg : "zlib error"); - if (0 != getdata((char*&)zdata.next_out, zdata.avail_out,cb)) { + if (0 != getdata((char*&)zdata.next_out, zdata.avail_out,cb,context)) { inflateEnd(&zdata); throw std::string("Can't allocate output buffer"); } int zerr = Z_OK; while (Z_OK == (zerr = inflate(&zdata,0))) { - if (0 != getdata((char*&)zdata.next_out, zdata.avail_out,cb)) { + if (0 != getdata((char*&)zdata.next_out, zdata.avail_out,cb,context)) { inflateEnd(&zdata); throw std::string("Can't allocate output buffer"); } @@ -499,12 +499,12 @@ sdata.avail_in = size - 1; RLCOMP_init(&sdata); - if (0 != getdata(sdata.next_out, sdata.avail_out,cb)) { + if (0 != getdata(sdata.next_out, sdata.avail_out,cb,context)) { throw std::string("Can't allocate output buffer"); } while (!RLCOMP_decompress(&sdata)) { - if (0 != getdata(sdata.next_out, sdata.avail_out,cb)) { + if (0 != getdata(sdata.next_out, sdata.avail_out,cb,context)) { throw std::string("Can't allocate output buffer"); } } From brukman at cs.uiuc.edu Mon Oct 4 12:36:45 2004 From: brukman at cs.uiuc.edu (Misha Brukman) Date: Mon, 4 Oct 2004 12:36:45 -0500 Subject: [llvm-commits] CVS: llvm/docs/OpenProjects.html Message-ID: <200410041736.MAA12304@zion.cs.uiuc.edu> Changes in directory llvm/docs: OpenProjects.html updated: 1.36 -> 1.37 --- Log message: Add example 'abstract' architectures for LLI: MIX, MMIX, and DLX --- Diffs of the changes: (+5 -2) Index: llvm/docs/OpenProjects.html diff -u llvm/docs/OpenProjects.html:1.36 llvm/docs/OpenProjects.html:1.37 --- llvm/docs/OpenProjects.html:1.36 Fri Oct 1 17:25:28 2004 +++ llvm/docs/OpenProjects.html Mon Oct 4 12:36:35 2004 @@ -344,7 +344,10 @@
  • Convert the non-functional Skeleton target to become an abstract machine target (choose some simple instructions, a register set, etc). This will become a much more useful example of a backend since it would be a simple - but functional backend.
  • + but functional backend. Examples of such architectures include MIX, + MMIX, DLX, + or come up with your own!
  • Use the new Skeleton backend in the Interpreter: compile LLVM to Skeleton target, and then interpret that code instead of LLVM. Performance win would be the primary goal, as the number of registers would be a small constant @@ -365,7 +368,7 @@ Chris Lattner
    LLVM Compiler Infrastructure
    - Last modified: $Date: 2004/10/01 22:25:28 $ + Last modified: $Date: 2004/10/04 17:36:35 $ From reid at x10sys.com Mon Oct 4 12:45:54 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 12:45:54 -0500 Subject: [llvm-commits] CVS: llvm/lib/Support/Compressor.cpp Message-ID: <200410041745.MAA12427@zion.cs.uiuc.edu> Changes in directory llvm/lib/Support: Compressor.cpp updated: 1.3 -> 1.4 --- Log message: Excise the ill-advised RLCOMP compression algorithm and simply leave the previously temporary NULLCOMP implementation that merely copies the data verbatim without compression. Also, don't warn if there's no compression library as that is taken care of during configuration time. --- Diffs of the changes: (+20 -159) Index: llvm/lib/Support/Compressor.cpp diff -u llvm/lib/Support/Compressor.cpp:1.3 llvm/lib/Support/Compressor.cpp:1.4 --- llvm/lib/Support/Compressor.cpp:1.3 Mon Oct 4 12:29:25 2004 +++ llvm/lib/Support/Compressor.cpp Mon Oct 4 12:45:44 2004 @@ -26,12 +26,6 @@ #include #endif -#ifndef HAVE_BZIP2 -# ifndef HAVE_ZLIB -# warning No compression library is available!! -# endif -#endif - namespace { inline int getdata(char*& buffer, unsigned& size, @@ -45,19 +39,13 @@ } //===----------------------------------------------------------------------===// -//=== RLCOMP - very simple run length compression scheme -//=== The code below transforms the input into blocks that are either -//=== compressed or not. Each block starts with a header byte that provides -//=== the length of the block. Values < 128 are uncompressed, values >128 -//=== are compressed. The value 128 is illegal. Currently, the algorithm is -//=== not completed and is #if'd out. +//=== NULLCOMP - a compression like set of routines that just copies data +//=== without doing any compression. This is provided so that if the +//=== configured environment doesn't have a compression library the +//=== program can still work, albeit using more data/memory. //===----------------------------------------------------------------------===// -enum { - MAX_RLCOMP_OUT = 32768 -}; - -struct RLCOMP_stream { +struct NULLCOMP_stream { // User provided fields char* next_in; unsigned avail_in; @@ -66,110 +54,19 @@ // Information fields uint64_t output_count; // Total count of output bytes - -#if 0 - // Algorithm fields - unsigned block_len; // Length of current block - unsigned compression; // State of compression 0=no, 1=yes, 2=indeterminate - char buffer[128]; // compression buffer (not used for decompress) - unsigned buflen; // bytes in compression buffer - bool pending; // is data pending to be written - char pending_data; // the pending data - unsigned clen; // length of the compressed block -#endif }; -void RLCOMP_init(RLCOMP_stream* s) { +void NULLCOMP_init(NULLCOMP_stream* s) { s->output_count = 0; -#if 0 - s->block_len = 0; - s->compression = 2; - s->buflen = 0; - s->pending = false; - s->pending_data = 0; - s->clen = 0; -#endif -} - -inline bool RLCOMP_getchar(RLCOMP_stream* s, unsigned& data) { -#if 0 - if (s->avail_in) { - data = *s->next_in++; - s->avail_in--; - return true; - } -#endif - return false; -} - -inline bool RLCOMP_putchar(RLCOMP_stream* s, unsigned data) { -#if 0 - if (s->avail_out) { - *s->next_out++ = data; - s->avail_out--; - s->output_count++; - return true; - } else { - s->pending = true; - s->pending_data = data; - return false; - } -#else - return false; -#endif } -bool RLCOMP_compress(RLCOMP_stream* s) { - assert(s && "Invalid RLCOMP_stream"); +bool NULLCOMP_compress(NULLCOMP_stream* s) { + assert(s && "Invalid NULLCOMP_stream"); assert(s->next_in != 0); assert(s->next_out != 0); assert(s->avail_in >= 1); assert(s->avail_out >= 1); -#if 0 - - // Handle pending data from the last time in - if (s->pending) { - RLCOMP_putchar(s,s->pending_data); - s->pending = false; - } - - unsigned c = 0; - unsigned lastc = 0; - // Handle the degenerate len=1 case - if (!RLCOMP_getchar(s,lastc)) { - RLCOMP_putchar(s,1); - return RLCOMP_putchar(s,lastc); - } - - while (RLCOMP_getchar(s,c)) { - switch(s->compression) { - case 0: - if (lastc == c) { - s->compression = 1; - s->clen = 2 ; - } else { - if (!RLCOMP_putchar(s, c)) - return false; - } - break; - - case 1: - if (lastc != c) { - s->compression = 2; - if (!RLCOMP_putchar(s, s->clen)) - return false; - } else { - s->clen++; - } - break; - - case 2: - break; - } - lastc = c; - } -#endif if (s->avail_out >= s->avail_in) { ::memcpy(s->next_out, s->next_in, s->avail_in); s->output_count += s->avail_in; @@ -187,49 +84,13 @@ } } -bool RLCOMP_decompress(RLCOMP_stream* s) { - assert(s && "Invalid RLCOMP_stream"); +bool NULLCOMP_decompress(NULLCOMP_stream* s) { + assert(s && "Invalid NULLCOMP_stream"); assert(s->next_in != 0); assert(s->next_out != 0); assert(s->avail_in >= 1); assert(s->avail_out >= 1); -#if 0 - unsigned c = 0; - while (RLCOMP_getchar(s,c)) { - switch(s->compression) { - case 0: // This is not a compressed block - s->block_len--; - if (!RLCOMP_putchar(s,c)) - return false; - break; - - case 1: // This is a comperssed block - while (s->block_len-- > 0) - if (!RLCOMP_putchar(s,c)) - return false; - break; - - case 2: // This is the length field - if (c < 128) { - s->compression = 0; - s->block_len = c; - } else { - s->compression = 1; - s->block_len = c - 128; - } - continue; - - default: // oops! - throw std::string("Invalid compression state"); - } - if (s->block_len <= 0) - s->compression = 2; - } - - if (s->repeat > 0) - throw std::string("Invalid compression state"); -#endif if (s->avail_out >= s->avail_in) { ::memcpy(s->next_out, s->next_in, s->avail_in); s->output_count += s->avail_in; @@ -247,7 +108,7 @@ } } -void RLCOMP_end(RLCOMP_stream* strm) { +void NULLCOMP_end(NULLCOMP_stream* strm) { } } @@ -275,7 +136,7 @@ bzdata.avail_in = size; bzdata.next_out = 0; bzdata.avail_out = 0; - switch ( BZ2_bzCompressInit(&bzdata, 9, 0, 0) ) { + switch ( BZ2_bzCompressInit(&bzdata, 9, 0, 100) ) { case BZ_CONFIG_ERROR: throw std::string("bzip2 library mis-compiled"); case BZ_PARAM_ERROR: throw std::string("Compressor internal error"); case BZ_MEM_ERROR: throw std::string("Out of memory"); @@ -365,10 +226,10 @@ } case COMP_TYPE_SIMPLE: { - RLCOMP_stream sdata; + NULLCOMP_stream sdata; sdata.next_in = in; sdata.avail_in = size; - RLCOMP_init(&sdata); + NULLCOMP_init(&sdata); if (0 != getdata(sdata.next_out, sdata.avail_out,cb,context)) { throw std::string("Can't allocate output buffer"); @@ -377,14 +238,14 @@ *(sdata.next_out++) = COMP_TYPE_SIMPLE; sdata.avail_out--; - while (!RLCOMP_compress(&sdata)) { + while (!NULLCOMP_compress(&sdata)) { if (0 != getdata(sdata.next_out, sdata.avail_out,cb,context)) { throw std::string("Can't allocate output buffer"); } } result = sdata.output_count + 1; - RLCOMP_end(&sdata); + NULLCOMP_end(&sdata); break; } default: @@ -494,23 +355,23 @@ } case COMP_TYPE_SIMPLE: { - RLCOMP_stream sdata; + NULLCOMP_stream sdata; sdata.next_in = in; sdata.avail_in = size - 1; - RLCOMP_init(&sdata); + NULLCOMP_init(&sdata); if (0 != getdata(sdata.next_out, sdata.avail_out,cb,context)) { throw std::string("Can't allocate output buffer"); } - while (!RLCOMP_decompress(&sdata)) { + while (!NULLCOMP_decompress(&sdata)) { if (0 != getdata(sdata.next_out, sdata.avail_out,cb,context)) { throw std::string("Can't allocate output buffer"); } } result = sdata.output_count; - RLCOMP_end(&sdata); + NULLCOMP_end(&sdata); break; } From reid at x10sys.com Mon Oct 4 12:48:47 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 12:48:47 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/Config/config.h.in Message-ID: <200410041748.MAA12471@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/Config: config.h.in updated: 1.30 -> 1.31 --- Log message: Add HAVE_BZIP2 and HAVE_ZLIB --- Diffs of the changes: (+6 -0) Index: llvm/include/llvm/Config/config.h.in diff -u llvm/include/llvm/Config/config.h.in:1.30 llvm/include/llvm/Config/config.h.in:1.31 --- llvm/include/llvm/Config/config.h.in:1.30 Fri Sep 24 16:19:06 2004 +++ llvm/include/llvm/Config/config.h.in Mon Oct 4 12:48:37 2004 @@ -21,6 +21,9 @@ /* Does not have bi-directional iterator */ #undef HAVE_BI_ITERATOR +/* Define if bzip2 library is available on this platform. */ +#undef HAVE_BZIP2 + /* Define to 1 if you have the header file. */ #undef HAVE_DLFCN_H @@ -197,6 +200,9 @@ /* Define to 1 if you have the header file. */ #undef HAVE_WINDOWS_H +/* Define if zlib library is available on this platform. */ +#undef HAVE_ZLIB + /* Installation directory for binary executables */ #undef LLVM_BINDIR From reid at x10sys.com Mon Oct 4 12:49:30 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 12:49:30 -0500 Subject: [llvm-commits] CVS: llvm/Makefile.config.in Message-ID: <200410041749.MAA12489@zion.cs.uiuc.edu> Changes in directory llvm: Makefile.config.in updated: 1.32 -> 1.33 --- Log message: Fix typo in makefile variable name that prevents zlib from being recognized --- Diffs of the changes: (+1 -1) Index: llvm/Makefile.config.in diff -u llvm/Makefile.config.in:1.32 llvm/Makefile.config.in:1.33 --- llvm/Makefile.config.in:1.32 Mon Oct 4 02:05:06 2004 +++ llvm/Makefile.config.in Mon Oct 4 12:49:19 2004 @@ -157,7 +157,7 @@ # Handle configured libraries HAVE_BZIP2 := @HAVE_BZIP2@ -HAVE_ZILB := @HAVE_ZLIB@ +HAVE_ZLIB := @HAVE_ZLIB@ # Installation directories, as provided by the configure script. exec_prefix = @exec_prefix@ From reid at x10sys.com Mon Oct 4 13:03:06 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 13:03:06 -0500 Subject: [llvm-commits] CVS: llvm/autoconf/configure.ac Message-ID: <200410041803.NAA12734@zion.cs.uiuc.edu> Changes in directory llvm/autoconf: configure.ac updated: 1.121 -> 1.122 --- Log message: Move the warning about no compression library down to the bottom, away from the fray, so it gets noticed. This commit is made without the corresponding configure script commit because it doesn't affect functionality and we don't want to force everyone into another reconfigure --- Diffs of the changes: (+9 -7) Index: llvm/autoconf/configure.ac diff -u llvm/autoconf/configure.ac:1.121 llvm/autoconf/configure.ac:1.122 --- llvm/autoconf/configure.ac:1.121 Mon Oct 4 02:05:07 2004 +++ llvm/autoconf/configure.ac Mon Oct 4 13:02:55 2004 @@ -257,14 +257,7 @@ fi if test $bzip2_found -eq 1 ; then AC_DEFINE([HAVE_BZIP2],[1],[Define if bzip2 library is available on this platform.]) -else - if test $zlib_found -ne 1 ; then - AC_MSG_WARN([**** Neither zlib nor bzip2 compression libraries were found - - archives will not support compression! Install bzip2 or zlib - and then reconfigure to ensure compatibility]) - fi fi - dnl dlopen() is required for plugin support. AC_SEARCH_LIBS(dlopen,dl,AC_DEFINE([HAVE_DLOPEN],[1],[Define if dlopen() is available on this platform.]),AC_MSG_WARN([dlopen() not found - disabling plugin support])) @@ -453,6 +446,15 @@ dnl Create the output files AC_OUTPUT +dnl Warn if we don't have a compression library +if test $bzip2_found -ne 1 ; then + if test $zlib_found -ne 1 ; then + AC_MSG_WARN([*** Neither zlib nor bzip2 compression libraries were found.]) + AC_MSG_WARN([*** Bytecode archives will not support compression!]) + AC_MSG_WARN([*** To correct, install the libraries and and re-run configure.]) + fi +fi + dnl Warn loudly if llvm-gcc was not obviously working if test $llvmgccwarn = yes then From lattner at cs.uiuc.edu Mon Oct 4 13:10:27 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 13:10:27 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/Support/DataTypes.h.in Message-ID: <200410041810.NAA28794@apoc.cs.uiuc.edu> Changes in directory llvm/include/llvm/Support: DataTypes.h.in updated: 1.10 -> 1.11 --- Log message: Fix #include flavor --- Diffs of the changes: (+1 -1) Index: llvm/include/llvm/Support/DataTypes.h.in diff -u llvm/include/llvm/Support/DataTypes.h.in:1.10 llvm/include/llvm/Support/DataTypes.h.in:1.11 --- llvm/include/llvm/Support/DataTypes.h.in:1.10 Fri Sep 24 08:28:49 2004 +++ llvm/include/llvm/Support/DataTypes.h.in Mon Oct 4 13:10:16 2004 @@ -21,7 +21,7 @@ #ifndef SUPPORT_DATATYPES_H #define SUPPORT_DATATYPES_H -#include +#include "llvm/Config/config.h" // Note that this header's correct operation depends on __STDC_LIMIT_MACROS // being defined. We would define it here, but in order to prevent Bad Things From lattner at cs.uiuc.edu Mon Oct 4 13:10:27 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 13:10:27 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/ADT/hash_map.in hash_set.in ilist Message-ID: <200410041810.NAA28817@apoc.cs.uiuc.edu> Changes in directory llvm/include/llvm/ADT: hash_map.in updated: 1.3 -> 1.4 hash_set.in updated: 1.3 -> 1.4 ilist updated: 1.21 -> 1.22 --- Log message: Fix #include flavor --- Diffs of the changes: (+3 -3) Index: llvm/include/llvm/ADT/hash_map.in diff -u llvm/include/llvm/ADT/hash_map.in:1.3 llvm/include/llvm/ADT/hash_map.in:1.4 --- llvm/include/llvm/ADT/hash_map.in:1.3 Fri Sep 24 13:28:00 2004 +++ llvm/include/llvm/ADT/hash_map.in Mon Oct 4 13:10:14 2004 @@ -65,6 +65,6 @@ // out specializations like stl_bvector.h, causing link conflicts. #include -#include +#include "llvm/ADT/HashExtras.h" #endif Index: llvm/include/llvm/ADT/hash_set.in diff -u llvm/include/llvm/ADT/hash_set.in:1.3 llvm/include/llvm/ADT/hash_set.in:1.4 --- llvm/include/llvm/ADT/hash_set.in:1.3 Fri Sep 24 13:28:00 2004 +++ llvm/include/llvm/ADT/hash_set.in Mon Oct 4 13:10:14 2004 @@ -66,6 +66,6 @@ // out specializations like stl_bvector.h, causing link conflicts. #include -#include +#include "llvm/ADT/HashExtras.h" #endif Index: llvm/include/llvm/ADT/ilist diff -u llvm/include/llvm/ADT/ilist:1.21 llvm/include/llvm/ADT/ilist:1.22 --- llvm/include/llvm/ADT/ilist:1.21 Wed Sep 1 17:55:34 2004 +++ llvm/include/llvm/ADT/ilist Mon Oct 4 13:10:14 2004 @@ -38,7 +38,7 @@ #ifndef LLVM_ADT_ILIST #define LLVM_ADT_ILIST -#include +#include "llvm/ADT/iterator" #include namespace llvm { From lattner at cs.uiuc.edu Mon Oct 4 13:10:29 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 13:10:29 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/System/TimeValue.h Message-ID: <200410041810.NAA29150@apoc.cs.uiuc.edu> Changes in directory llvm/include/llvm/System: TimeValue.h updated: 1.2 -> 1.3 --- Log message: Fix #include flavor --- Diffs of the changes: (+1 -1) Index: llvm/include/llvm/System/TimeValue.h diff -u llvm/include/llvm/System/TimeValue.h:1.2 llvm/include/llvm/System/TimeValue.h:1.3 --- llvm/include/llvm/System/TimeValue.h:1.2 Sat Sep 25 03:29:54 2004 +++ llvm/include/llvm/System/TimeValue.h Mon Oct 4 13:10:18 2004 @@ -11,7 +11,7 @@ // //===----------------------------------------------------------------------===// -#include +#include "llvm/Support/DataTypes.h" #ifndef LLVM_SYSTEM_TIMEVALUE_H #define LLVM_SYSTEM_TIMEVALUE_H From lattner at cs.uiuc.edu Mon Oct 4 14:52:23 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:52:23 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ Message-ID: <200410041952.OAA12758@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++ added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:52:34 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:52:34 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/README.txt Message-ID: <200410041952.OAA12768@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++: README.txt added (r1.1) --- Log message: New file --- Diffs of the changes: (+3 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/README.txt diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/README.txt:1.1 *** /dev/null Mon Oct 4 14:52:31 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/README.txt Mon Oct 4 14:52:21 2004 *************** *** 0 **** --- 1,3 ---- + These benchmarks were downloaded from: + http://www.prolangs.rutgers.edu/public.html + From lattner at cs.uiuc.edu Mon Oct 4 14:52:39 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:52:39 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/ Message-ID: <200410041952.OAA12773@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:01 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:01 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/ Message-ID: <200410041953.OAA12818@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/city: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/city added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/ Message-ID: <200410041953.OAA12826@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2 added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/ Message-ID: <200410041953.OAA12823@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1 added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:01 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:01 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/ Message-ID: <200410041953.OAA12817@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/ Message-ID: <200410041953.OAA12829@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/ Message-ID: <200410041953.OAA12832@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/family: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/family added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/ Message-ID: <200410041953.OAA12835@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/ Message-ID: <200410041953.OAA12839@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ Message-ID: <200410041953.OAA12850@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/garage/ Message-ID: <200410041953.OAA12838@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/garage: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/garage added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/ Message-ID: <200410041953.OAA12840@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/life: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/life added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/ Message-ID: <200410041953.OAA12857@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/ Message-ID: <200410041953.OAA12853@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/office: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/office added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/ Message-ID: <200410041953.OAA12864@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/ Message-ID: <200410041953.OAA12856@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/ Message-ID: <200410041953.OAA12847@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/ Message-ID: <200410041953.OAA12868@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 14:53:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 14:53:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/ Message-ID: <200410041953.OAA12862@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 15:01:21 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:21 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp Message-ID: <200410042001.PAA13089@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP: NP.cpp added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+35 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp:1.1 *** /dev/null Mon Oct 4 15:01:20 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp Mon Oct 4 15:01:10 2004 *************** *** 0 **** --- 1,35 ---- + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + // Written by Hemant Pande, Rutgers University. December 1994. May be + // distributed freely, provided this comment is displayed at the top. + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + class True { + public: + True() {} + virtual True *and (True *arg) + { + return arg; + } + } true; + + class False : public True { + public: + False() {} + True *and (True *arg); + } false; + + True *False::and (True *arg) + { + return &false; + } + + True *v1, *nv1, *v2, *nv2, *v3, *nv3; + True *c; + + main () { + if (0) {v1 = &true; nv1 = &false;} else {v1 = &false; nv1= &true;} + if (0) {v2 = &true; nv2 = &false;} else {v2 = &false; nv2 = &true;} + if (0) {v3 = &true; nv3 = &false;} else {v3 = &false; nv3 = &true;} + if (0) c = nv2; else if (0) c = v1; else c = v2; + if (0) c = c->and(nv3); else if (0) c = c->and(nv2); else c = c->and(v1); + if (0) c = c->and(v2); else if (0) c = c->and(nv1); else c = c->and(v3); + } From lattner at cs.uiuc.edu Mon Oct 4 15:01:28 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:28 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/fsm.cpp Message-ID: <200410042001.PAA13199@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm: fsm.cpp added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+102 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/fsm.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/fsm.cpp:1.1 *** /dev/null Mon Oct 4 15:01:24 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/fsm.cpp Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,102 ---- + // Obtained from "C++ Programming Style" by Tom Cargill, + // Addison Wesley Publishing Company, Inc. 1992 Edition + // Chapter 8, Listing 8.7 + + #include + #include + const int range = CHAR_MAX + 1; // 0x7F + 1; + + class state { + public: + state *transition[range]; + state(); + }; + + class triple { + public: + int from, to; + char input; + }; + + class fsm { + state *graph; + state *current; + public: + void reset(); + void advance(char); + int end_state(); + int doom_state(); + fsm(triple*); + virtual ~fsm(); + }; + + state::state() { + for (int i = 0; i < range; ++i) + transition[i] = 0; + } + + fsm::fsm(triple *p) { + int max_node = 0; + for (triple *e = p; e->from; ++e) { + if (e->from > max_node) + max_node = e->from; + if (e->to > max_node) + max_node = e->to; + } + graph = new state[max_node+1]; // was new state[max_node+1] + for (e=p; e->from; ++e) + graph[e->from].transition[e->input] = &graph[e->to]; + current = 0; + } + + fsm::~fsm() { + delete [] graph; + } + + void fsm::reset() { + current = &graph[1]; + } + + void fsm::advance(char x) { + if (current) + current = current->transition[x]; + } + + int fsm::end_state() { + return current==&graph[0]; + } + + int fsm::doom_state() { + return current==0; + } + + class sample : public fsm { + static triple edges[]; + public: + sample(); + }; + + triple sample::edges[] = {{1,'A',2}, {1, 'B', 3}}; + + sample::sample() : fsm(edges) { + } + + #include + + main() { + char input_string[80]; + printf("Enter input expression: "); + scanf("%s", input_string); + sample m; + m.reset(); + int index = 0; + m.advance(input_string[index++]); + while (!m.end_state() && !m.doom_state()) { + m.advance(input_string[index++]); + } + if (m.end_state()) + printf("\nValid input expression"); + else + printf("\nInvalie input expression"); + return 0; + } From lattner at cs.uiuc.edu Mon Oct 4 15:01:29 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:29 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/README dosgreed.cpp dosgreed.hpp greed.hpp Message-ID: <200410042001.PAA13238@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed: README added (r1.1) dosgreed.cpp added (r1.1) dosgreed.hpp added (r1.1) greed.hpp added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+971 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/README diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/README:1.1 *** /dev/null Mon Oct 4 15:01:24 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/README Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,3 ---- + Obtained from Dinesh Adithan of Tata Consultancy Services, Pune, India. + The game of "greed" for DOS. Source unknown (perhaps known to Dinesh). + August, 1993 : Hemant Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/dosgreed.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/dosgreed.cpp:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/dosgreed.cpp Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,799 ---- + // the DOS version of GREED + + #include "dosgreed.hpp" + + + // greed member function definitions + + char *strcpy(char *str1, char *str2) {return "";} + char *strcat(char *str1, char *str2) {return "";} + + static char sBuffer [BUFFER_SIZE]; + + // greed class definitions + + // ********************************************************************** + static void code (char *buffer, int size) + { + for (size--; size >= 0; size--) + buffer [size] ^= 0x5A; + } + + + // ********************************************************************** + uchar Greed::GetPlayTable (uint X, uint Y) + { + return cPlayTable [Y * nMaxX + X]; + } + + + // ********************************************************************** + uchar Greed::SetPlayTable (uint X, uint Y, uchar Value) + { + return cPlayTable [Y * nMaxX + X] = Value; + } + + + // ********************************************************************** + int Greed::GetCurrentScore (void) + { + return nScore; + } + + + // ********************************************************************** + int Greed::GetSeed (void) + { + return iSeed; + } + + + // ********************************************************************** + int Greed::IsHighScore (void) + { + // returns MAX_SCORE if not a high score + // else returns position in the score table + + for (int i = MAX_SCORE - 1; i >= 0; i--) + if (nScore <= ScoreCard [i].nScore) + return i + 1; + return 0; + } // end of IsHighScore + + + // ********************************************************************** + void Greed::InsertHighScore (char *pszName) + { + int pos; + + // check if really a high score + pos = IsHighScore (); + if (pos == MAX_SCORE) + return; + + // insert the new score displacing the last one + for (int i = MAX_SCORE - 1; i > pos; i--) { + strcpy(ScoreCard [i].szName, ScoreCard [i - 1].szName); + ScoreCard [i].nScore = ScoreCard [i - 1].nScore; + ScoreCard [i].iSeed = ScoreCard [i - 1].iSeed; + } + + // copy the new name + ScoreCard [pos].nScore = nScore; + ScoreCard [pos].iSeed = iSeed; + strcpy (ScoreCard [pos].szName, pszName); + + // encode the score file + strcpy(sBuffer,"game"); + code (sBuffer, SCORE_CARD_SIZE); + + // save the file + // WriteFile (szScoreFile, sBuffer, SCORE_CARD_SIZE); + } // end of InsetHighScore + + + // ********************************************************************** + Score *Greed::GetHighScore (int Pos) + { + return &ScoreCard [(Pos >= 0 && Pos < MAX_SCORE) ? Pos : 0]; + } // end of GetHighScore + + + // ********************************************************************** + int Greed::AddScore (int nDeltaX, int nDeltaY) + { + // calculates the score to be added depending upon the direction of move + // returns number of moves to make; 0 if no move possible + + int nNewXPos, nNewYPos; + + nNewXPos = nXPos + nDeltaX; + nNewYPos = nYPos + nDeltaY; + + // is X out of range + if (nNewXPos < 0 || nNewXPos >= nMaxX) return 0; + + // is Y out of range + if (nNewYPos < 0 || nNewYPos >= nMaxY) return 0; + + uchar ucScoreInc = GetPlayTable (nNewXPos, nNewYPos); + + // is it an illegal position + if (ucScoreInc == '.') return 0; + + nScore += ucScoreInc - '0'; + + return ucScoreInc - '0'; + } // end of AddScore + + + // ********************************************************************** + int Greed::UpdateTable (int nDeltaX, int nDeltaY, int nNumber) + { + // update table i.e fill table with dots + // the number of dots are given by nNumber + // if table position is already filled with a dot then it returns TRUE + // else FALSE + + int nNewXPos, nNewYPos; + + if (nNumber == 0) + return TRUE; + + for (; nNumber > 0; nNumber --) { + // if out of range we should be at the same spot + nNewXPos = nXPos + nDeltaX; + nNewYPos = nYPos + nDeltaY; + + // is X out of range + if (nNewXPos < 0 || nNewXPos >= nMaxX) return TRUE; + + // is Y out of range + if (nNewYPos < 0 || nNewYPos >= nMaxY) return TRUE; + + // in range + nXPos = nNewXPos; nYPos = nNewYPos; + + // is it an illegal position ? + if (GetPlayTable (nXPos, nYPos) == '.') return TRUE; + + SetPlayTable (nXPos, nYPos, '.'); + + UpdateScreen (); + }; + + return FALSE; + } // end of UpdateTable + + + // ********************************************************************** + void Greed::FillTable (void) + { + // fills up the table with random numbers; no zeroes allowed + // also sets up initial X and Y position + + // srand (iSeed); sets random seed + + int nPosition = 0,i; + char szBuffer [10]; // buffer for sprintf + + char bFilled = FALSE; + + while (!bFilled) { + strcpy(szBuffer, "game"); + + i=0; + while (szBuffer[i]) { + if (szBuffer[i] != '0') + cPlayTable [nPosition++] = szBuffer[i]; + + i++; + + if (nPosition >= (nMaxX * nMaxY)) { + bFilled = TRUE; + cPlayTable [nPosition] = '\0'; + break; + } + } + } + + nXPos = 50 % nMaxX; + nYPos = 50 % nMaxY; + } // end of FillTable + + + // ********************************************************************** + void Greed::NewGame (int Seed) + { + // used at start of game to fill up the table and update the screen + + iSeed = Seed; + FillTable (); + + nScore = GetPlayTable (nXPos, nYPos) - '0'; + SetPlayTable (nXPos, nYPos, '.'); + + FillScreen (); + } // end of NewGame + + + // ********************************************************************** + int Greed::SaveGame (void) + { + // saves the current game + + strcpy(sBuffer,"game"); + + strcat (sBuffer, cPlayTable); + + code (sBuffer, SAVE_FILE_SIZE); + + // write to file + return 1; // WriteFile (szSaveFile, sBuffer, SAVE_FILE_SIZE); + } // end of SaveGame + + + // ********************************************************************** + int Greed::RestoreGame (void) + { + // restores the game + + if (strcpy(sBuffer,"game")) return TRUE; + + code (sBuffer, SAVE_FILE_SIZE); + + nScore = iSeed = nXPos = nYPos = nMaxX = nMaxY = 0; + + char *cTempPlayTable = "game"; + if (cTempPlayTable == 0) { + Error (0); + return TRUE; + } + + // free allocated table and allocate new size + cPlayTable = 0; + cPlayTable = cTempPlayTable; + + strcpy (cPlayTable, "game"); + FillScreen (); + return FALSE; + } + + + // ********************************************************************** + Greed::Greed (uint nXmax, uint nYmax, char *pszScoreFile, char *pszSaveFile) + { + + // checks validity of table size + nMaxX = (nXmax == 0) ? DEFAULT_X : nXmax; + nMaxY = (nYmax == 0) ? DEFAULT_Y : nYmax; + + cPlayTable = 0; + + if (pszScoreFile == 0 || *pszScoreFile == '\0') + strcpy (szScoreFile, DEFAULT_SCORE_FILE); + else + strcpy (szScoreFile, pszScoreFile); + + if (pszSaveFile == 0 || *pszSaveFile == '\0') + strcpy (szSaveFile, DEFAULT_SAVE_FILE); + else + strcpy (szSaveFile, pszSaveFile); + } // end of greed constructor + + + // ********************************************************************** + void Greed::Initialize (void) + { + + // Gets memory for the playing table + cPlayTable = "game"; + if (cPlayTable == 0) { + Error (0); + // exit (1); + } + cPlayTable [nMaxX * nMaxY + 1] = '\0'; + + NewGame (0); + + // initialize the score card + if (strcpy(sBuffer, "game")) { + // unable to read score file + // create new score card + Score dummy; + dummy.szName [0] = '\0'; + dummy.nScore = 0; + dummy.iSeed = 0; + + for (int i = 0; i < MAX_SCORE; i++) { + strcpy(ScoreCard [i].szName, dummy.szName); + ScoreCard [i].nScore = dummy.nScore; + ScoreCard [i].iSeed = dummy.iSeed; + } + } + + else { + code (sBuffer, SCORE_CARD_SIZE); + strcpy(sBuffer,"game"); + } + } + + + // ********************************************************************** + Greed::~Greed (void) + { + if (cPlayTable) cPlayTable=0;; + } + + + // ********************************************************************** + int Greed::MoveNorth (void) + { + return UpdateTable ( 0, -1, AddScore ( 0, -1)); + } + + int Greed::MoveSouth (void) + { + return UpdateTable ( 0, 1, AddScore ( 0, 1)); + } + + int Greed::MoveEast (void) + { + return UpdateTable ( 1, 0, AddScore ( 1, 0)); + } + + int Greed::MoveWest (void) + { + return UpdateTable (-1, 0, AddScore (-1, 0)); + } + + int Greed::MoveNorthEast (void) + { + return UpdateTable ( 1, -1, AddScore ( 1, -1)); + } + + int Greed::MoveSouthEast (void) + { + return UpdateTable ( 1, 1, AddScore ( 1, 1)); + } + + int Greed::MoveNorthWest (void) + { + return UpdateTable (-1, -1, AddScore (-1, -1)); + } + + int Greed::MoveSouthWest (void) + { + return UpdateTable (-1, 1, AddScore (-1, 1)); + } + // ********************************************************************** + void Dosgreed::UpdateScreen (void) + { + #if 0 + // updates screen and score + gotoxy (nXPos + 1, nYPos + 1); + putch ('.'); + + gotoxy (8, nMaxY + 1); clreol (); + + cprintf ("%d", GetCurrentScore ()); + + // restore cursor back to its position + gotoxy (nXPos + 1, nYPos + 1); + #endif + } // end of UpdateScreen + + + // ********************************************************************** + void Dosgreed::FillScreen (void) + { + #if 0 + // fills screen with the numbers and shows initial score + + clrscr (); + + for (int Y = 0; Y < nMaxY; Y++) { + int CurrY = wherey (); // find current Y position + + for (int X = 0; X < nMaxX; X++) // display one line + putch (GetPlayTable (X, Y)); + + // has cursor gone to the next line + if (wherey () == CurrY) { // if not make it go to + putch ('\n'); putch ('\r'); // the next line + } + } + + gotoxy (1, nMaxY + 1); clreol (); + cprintf ("Score: %d", GetCurrentScore ()); + + // restore cursor back to its position + gotoxy (nXPos + 1, nYPos + 1); + #endif + } // end of FillScree + + + // ********************************************************************** + void Dosgreed::GameEnd (void) + { + + int CurrScore; + char szName [22]; + + //gotoxy (nXPos + 1, nYPos + 1); + //putch ('*'); + + //SplSound (); + + MsgAtBot ("Viciously strike a key to continue"); + + CurrScore = IsHighScore (); + if (CurrScore < MAX_SCORE) { + //gotoxy (15, nMaxY + 1); clreol (); + //cputs ("Thou art a Greedy Pig; Enter thy name "); + + szName [0] = (char) 20; + // insert name + InsertHighScore ("a"); + //gotoxy (15, nMaxY + 1); clreol (); + + ShowScore (CurrScore); + MsgAtBot ("Viciously strike a key to continue"); + } + } // end of GameEnd + + + // ********************************************************************** + int Dosgreed::ReadFile (char *pszFileName, char *psBuffer, int iSize) + { + int iHandle; + int iBytesRead; + + iHandle = 1; //open (pszFileName, O_BINARY | O_RDWR | O_CREAT, + //S_IREAD | S_IWRITE); // flags for create file + + if (iHandle == -1) { // error in opening file + Error (0); + return TRUE; + } + + iBytesRead = 1; //read (iHandle, psBuffer, iSize); + + if (iBytesRead == -1) { // error in reading file + Error (0); + return TRUE; + } + + if (iBytesRead != iSize) { // invalid file + Error ("Could Not Read File"); + return TRUE; + } + + // close (iHandle); + return FALSE; + } // end of ReadFile + + + // ********************************************************************** + int Dosgreed::WriteFile (char *pszFileName, char *psBuffer, int iSize) + { + int iHandle; + int iBytesWritten; + + iHandle = 1; //open (pszFileName, O_BINARY | O_RDWR | O_CREAT | O_TRUNC, + // S_IREAD | S_IWRITE); // flags for create file + + + if (iHandle == -1) { // error in opening file + Error (0); + return TRUE; + } + + iBytesWritten = 1; // write (iHandle, psBuffer, iSize); + + if (iBytesWritten == -1) { // error in writing file + Error (0); + return TRUE; + } + + if (iBytesWritten != iSize) { // invalid file + Error ("Could Not Write File"); + } + + // close (iHandle); + return FALSE; + } // end of ReadFile + + + // ********************************************************************** + void Dosgreed::Error (int ErrorNo) + { + char *ErrMsg; + strcpy(ErrMsg,"err"); //strerror (ErrorNo); + // ErrMsg [strlen (ErrMsg) - 1] = '\0'; + + MsgAtBot (ErrMsg); + } // end of function Error + + + // ********************************************************************** + void Dosgreed::Error (char *ErrorMsg) + { + MsgAtBot (ErrorMsg); + } + + + // ********************************************************************** + void Dosgreed::ShowScore (int HighLight) + { + // Highlight = -1 if no high light wanted + const ScoreStart = 7; + + //window (10, ScoreStart, 70, ScoreStart + MAX_SCORE + 2); + //textcolor (BLUE); textbackground (CYAN); + //clrscr (); + + // show heading + //window (13, ScoreStart, 70, ScoreStart + MAX_SCORE + 2); + //cprintf (" The Top Ten Pigs\n\r"); + //cprintf ("%-5s%-30s%-10s%-10s", "No", "Name", "Seed", "Score"); + + //window (13, ScoreStart + 2, 70, ScoreStart + MAX_SCORE + 2); + //textcolor (YELLOW); + + // show hi scores + Score *HiScore; + + for (int i = 0; i < MAX_SCORE; i++) { + HiScore = GetHighScore (i); + //gotoxy (1, i + 1); + //cprintf ("%-5d%-30s%-10d%-10d", i + 1, HiScore.szName, + // HiScore.iSeed, HiScore.nScore); + } + + //window (11, ScoreStart + 2, 70, ScoreStart + MAX_SCORE + 2); + if (HighLight != -1) { + //gotoxy (1, HighLight + 1); + //putch ('*'); + } + + // restore window + // struct text_info TextInfo; + + // gettextinfo (&TextInfo); + + // window (1, 1, TextInfo.screenwidth, TextInfo.screenheight); + // textcolor (LIGHTGRAY); textbackground (BLACK); + } // end of function ShowScore + + + // ********************************************************************** + void Dosgreed::Setup (void) + { + // textmode (C4350); // VGA 50 line mode + + // textcolor (LIGHTGRAY); textbackground (BLACK); + nLastLine = DEFAULT_Y + 1; + nLastCol = DEFAULT_X; + // randomize (); + + Initialize (); + } + + + // ********************************************************************** + void Dosgreed::PlayGame (void) + { + int bGameEnd = FALSE; + + char ch1, ch2; + + Setup (); + + for (;;) { + while (! bGameEnd) { + ch1 = 'a'; // tolower (getch ()); + + if (ch1 == 0) + ch2 = 'b'; // getch (); + else + ch2 = ch1; + + bGameEnd = MoveNorthWest (); + bGameEnd = MoveNorth (); + bGameEnd = MoveNorthEast (); + bGameEnd = MoveWest (); + bGameEnd = MoveEast (); + bGameEnd = MoveSouthWest (); + bGameEnd = MoveSouth (); + bGameEnd = MoveSouthEast (); + ShowHelp (); + FillScreen (); + if (SaveGame ()) + Error ("Game could not be Saved"); + if (RestoreGame ()) + Error ("Game could not be Restored"); + ShowScore (-1); + FillScreen (); + NewGame (0); + { + int Number; + Number = GetInteger (); + + if (Number != -1) // valid number + NewGame (Number); + else + FillScreen (); + } + + if (bGameEnd) { + GameEnd (); + + do { + ch1 = 'c'; // toupper (getch ()); + //if (ch1 == 0) getch (); + } while (ch1 != 'N' && ch1 != 'Y'); + + if (ch1 == 'N') { + } + + else { + NewGame (0); + bGameEnd = FALSE; + } + } // end of check if game end + } // end of while loop + } // end of infinite loop + } // end of function PlayGame + + int SoundFlag = FALSE; + int nLastLine, nLastCol; + + + // ********************************************************************** + void Sound (void) + { + if (SoundFlag) { + //sound (340); delay (50); + //sound (240); delay (50); + //nosound (); + } + } + + + // ********************************************************************** + void SplSound (void) + { + if (SoundFlag) { + //sound (500); delay (50); + //sound (400); delay (50); + //sound (300); delay (50); + //sound (200); delay (50); + //nosound (); + } + } + + + // ********************************************************************** + void MsgAtBot (char *msg) + { + // displays a message in the middle of the last line of the screen + char ch; + int x, y, + NewXPos; + + x = 0; y = 0; // save current cursor posn + + NewXPos = (nLastCol - 0) >> 1; + NewXPos = (NewXPos > 12) ? NewXPos : 15;// should spill into Score: 12345 + + //gotoxy (NewXPos, nLastLine); + //cputs (msg); + + //ch = getch (); if (ch == 0) getch (); // flush extra keys + + //gotoxy (15, nLastLine); clreol (); + //gotoxy (x, y); + } + + + // ********************************************************************** + void ShowHelp (void) + { + #if 0 + // shows the help screen + window (9, 1, 72, 24); + textcolor (BROWN); textbackground (CYAN); + clrscr (); + window (11, 2, 70, 23); + cputs (" ?????????????????????????? Help ??????????????????????????\n\r"); + cputs (" ? ?\n\r"); + cputs (" ? Other Keys Playing Keys ?\n\r"); + cputs (" ? F1 This Help Screen ?\n\r"); + cputs (" ? Q W E ?\n\r"); + cputs (" ? F2 Save Game A D ?\n\r"); + cputs (" ? F3 Restore Game Z X C ?\n\r"); + cputs (" ? F4 Show High Scores ?\n\r"); + cputs (" ? 7 8 9 ?\n\r"); + cputs (" ? F5 New Game 4 6 ?\n\r"); + cputs (" ? F6 Enter A Seed 1 2 3 ?\n\r"); + cputs (" ? ?\n\r"); + cputs (" ? F7 Sound Toggle Home \x18 PgUp ?\n\r"); + cputs (" ? \x1B? ?\x1A ?\n\r"); + cputs (" ? F8 Dos Shell End \x19 PgDn ?\n\r"); + cputs (" ? ?\n\r"); + cputs (" ? Quits ?\n\r"); + cputs (" ??????????????????????????????????????????????????????????\n\r"); + cputs (" ? Dos Greed for Pigs ?\n\r"); + cputs (" ? written by ?\n\r"); + cputs (" ? Dinesh Adithan ?\n\r"); + cputs (" ??????????????????????????????????????????????????????????"); + + // restore window + struct text_info TextInfo; + + gettextinfo (&TextInfo); + + window (1, 1, TextInfo.screenwidth, TextInfo.screenheight); + textcolor (LIGHTGRAY); textbackground (BLACK); + #endif + } // end of function ShowHelp + + + // ********************************************************************** + int GetInteger (void) + { + return 0; + #if 0 + int size = 0; + char num [16], ch; + + do { + ch = getch (); + + switch (ch) { + case '0' : case '1' : case '2' : case '3' :case '4' : + case '5' : case '6' : case '7' : case '8' :case '9' : + if (size < 15) + putch (num [size++] = ch); + else + Sound (); + break; + + case '\b' : + if (size > 0) { + num [--size] = ' '; + cputs ("\b \b"); + } + else + Sound (); + break; + + case '\r' : + if (size > 0) { + num [size] = '\0'; + return atoi (num); + } + else + Sound (); + break; + + case 27 : // ESC key + return -1; + + default : + Sound (); + } + } while (TRUE); + #endif + } // end of function GetInteger + + + // ********************************************************************** + main () + { + Dosgreed PlayTable (DEFAULT_X, DEFAULT_Y /* can be 49 */); + + PlayTable.PlayGame (); + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/dosgreed.hpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/dosgreed.hpp:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/dosgreed.hpp Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,45 ---- + #ifndef DOSGREED_H + #define DOSGREED_H + + #include "greed.hpp" + + class Dosgreed : public Greed { + virtual void UpdateScreen (void); + virtual void Error (int ErrorNo); + virtual void Error (char *ErrorMsg); + + virtual int ReadFile (char *pszFileName, + char *psBuffer, int iSize); + virtual int WriteFile (char *pszFileName, + char *psBuffer, int iSize); + + public: + Dosgreed (uint nXmax, uint nYmax, + char *pszScoreFile = DEFAULT_SCORE_FILE, + char *pszSaveFile = DEFAULT_SAVE_FILE) + : Greed (nXmax, nYmax, + pszScoreFile, pszSaveFile) {}; + + void ShowScore (int HighLight); + // Highlight = -1 if no high light wanted + + void Setup (void); + void PlayGame (void); + virtual void GameEnd (void); + + virtual void FillScreen (void); + virtual ~Dosgreed () {}; + }; + + + // Support functions for PlayGame + extern void MsgAtBot (char *Message); + extern void Sound (void); + extern void SplSound (void); + extern void ShowHelp (void); + extern int GetInteger (void); + + extern int SoundFlag; + extern int nLastLine, nLastCol; + + #endif // of DOSGREED_H Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/greed.hpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/greed.hpp:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/greed.hpp Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,124 ---- + // Greed header file + // class definition and function prototypes + extern "C" { + char *strcpy(char *str1, char *str2); + char *strcat(char *str1, char *str2); + } + + #ifndef GREED_H + #define GREED_H + + + #ifndef TRUE + #define TRUE -1 + #endif + + #ifndef FALSE + #define FALSE 0 + #endif + + const DEFAULT_X = 80; // default dimensions + const DEFAULT_Y = 24; + + // buffer for encoding and decoding etc. + #define BUFFER_SIZE 4096 + + #define SCORE_CARD_SIZE (sizeof (Score) * MAX_SCORE) + #define SAVE_FILE_SIZE BUFFER_SIZE + + + typedef unsigned int uint; + typedef unsigned char uchar; + + const MAX_SCORE = 10; + + #define DEFAULT_SCORE_FILE "greed.sco" + #define DEFAULT_SAVE_FILE "greed.sav" + + + struct Score { + char szName [20]; + uint nScore; + int iSeed; + }; + + class Greed { + + private: + uint nScore; // current Score + int iSeed; // current seed + + char szScoreFile[256]; // the name of the score file + char szSaveFile[256]; // the name of the save game file + + Score ScoreCard [MAX_SCORE]; // the list of high scores + // 0 has highest score + void CheckScore (void); + + int AddScore (int nDeltaX, int nDeltaY); + // will return the number of moves to make besides adding the score + + int UpdateTable (int nDeltaX, int nDeltaY, int nNumber); + // will update table with dots + + void FillTable (void); + // randomly fills the table with the numbers seed is iSeed + + uchar SetPlayTable (uint X, uint Y, uchar Value); + // to set character in play table + // Private, cannot let others tamper with play table + + protected: + uint nXPos, nYPos; // current X and Y cursor position + uint nMaxX, nMaxY; // Max X and Y coordinates + // coordinates range from 0 - nMax[XY]-1 + + char *cPlayTable; // the two dimensional playing table + + uchar GetPlayTable (uint X, uint Y); + // to access characters in play table + + // pure virtual functions + virtual void UpdateScreen (void) = 0; + virtual void Error (int ErrorNo) = 0; + virtual void Error (char *ErrorMsg) = 0; + virtual int ReadFile (char *pszFileName, + char *psBuffer, int iSize) = 0; + virtual int WriteFile (char *pszFileName, + char *psBuffer, int iSize) = 0; + + public: + // constructor requires the size of the playing table, + // the names of the score file and the save file + Greed (uint nXmax, uint nYmax, + char *pszScoreFile = DEFAULT_SCORE_FILE, + char *pszSaveFile = DEFAULT_SAVE_FILE); + + virtual ~Greed (void); + + void Initialize (void); + + virtual void GameEnd (void) = 0; + virtual void FillScreen (void) = 0; + + // functions handling scores + int GetCurrentScore (void); + Score *GetHighScore (int Pos); + int IsHighScore (void); + void InsertHighScore (char *pszName); + + int GetSeed (void); + + int SaveGame (void); + int RestoreGame (void); + + void NewGame (int iSeed); + + int MoveNorth (void); int MoveSouth (void); + int MoveEast (void); int MoveWest (void); + int MoveNorthEast (void); int MoveNorthWest (void); + int MoveSouthEast (void); int MoveSouthWest (void); + }; + + + #endif // of GREED_H From lattner at cs.uiuc.edu Mon Oct 4 15:01:28 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:28 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.cpp student2.h Message-ID: <200410042001.PAA13190@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1: student2.cpp added (r1.1) student2.h added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+194 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.cpp:1.1 *** /dev/null Mon Oct 4 15:01:23 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.cpp Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,94 ---- + // Written for undergraduate C++ course project at Dept of + // Computer Science, Rutgers University. + + #include + #include + #include "student2.h" + void bin_op_expr::print_me() + { + cout << "("; + first->print_me(); + cout << op_name; + second->print_me(); + cout << ")"; + } + + double const_expr::eval(double at) + { + return value; + } + + expr *const_expr::deriv(strng var) + { + return (new const_expr(0)); + } + + double var_expr::eval(double at) + { + return at; + } + + expr *var_expr::deriv(strng var) + { + if (1) return (new const_expr(1)); // was strcmp between var and name + else return (new var_expr(name)); + + } + + double prod_expr::eval(double at) + { + return (first->eval(at) * second->eval(at)); + } + + expr *prod_expr::deriv(strng var) + { + return new sum_expr(new prod_expr(first, second->deriv(var)),new prod_expr(second, first->deriv(var))); + } + + double sum_expr::eval(double at) + { + return (first->eval(at) + second->eval(at)); + } + + expr *sum_expr::deriv(strng var) + { + expr *f; + return new sum_expr(f=first->deriv(var), second->deriv(var)); + } + + double quotient_expr::eval(double at) + { + return (first->eval(at) / second->eval(at)); + } + + expr *quotient_expr::deriv(strng var) + { + return new quotient_expr(new sum_expr(new prod_expr(second, first->deriv(var)), new prod_expr(new const_expr(-1), new prod_expr(first, second->deriv(var)))), new prod_expr(second, second)); + } + + main() { + const_expr c(8); + var_expr x("x"); + prod_expr simple(new const_expr(123.45), new var_expr("y")); + + cout << "c is "; + c.print_me(); + cout << "\n and its value at 3 is: " << + c.eval(3); + cout << "\n and its derivative with respect to x is: "; + c.deriv("x")->print_me(); + cout << "\nx is "; + x.print_me(); + cout << "\n and its value at 3 is: " << + x.eval(3); + cout << "\n and its derivative with respect to x is: "; + x.deriv("x")->print_me(); + cout << "\nsimple is "; + simple.print_me(); + cout << "\n and its value at 3 is: " << + simple.eval(3); + cout << "\n and its derivative with respect to y is: "; + simple.deriv("y")->print_me(); + cout << "\n and its derivative with respect to x is: "; + simple.deriv("x")->print_me(); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.h:1.1 *** /dev/null Mon Oct 4 15:01:28 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,100 ---- + /* this is file class-defs.h provided to students */ + + //extern "C" { + //char *strcpy(char *nam, char *str); + //} + + typedef char *strng; + + /* class expr is the top of the class heirarchy for expressions. Any + expression object will be an instance of some derived class which has + class expr as its base class (or as the base class of its base class...) + */ + class expr { + public: + expr(){} + ~expr(){} + virtual void print_me() = 0; + + /* This is the function that an expression object uses to print itself. + The version given here should never be run - the print function should + be redefined in the derived class */ + + virtual expr *deriv(char *var) = 0; + /* This is the function that an expression object uses to compute its + derivative with respect to "var". The version given here should never + be run - deriv() should be redefined in the derived class */ + + virtual double eval(double at) = 0; + /* This is the function that an expression object uses to compute its + value when all variables in it are replaced by the value of "at" + */ + + }; + + + /* an expression which is a numerical constant */ + class const_expr : public expr { + double value; + public: + const_expr(double v) {value = v;} + ~const_expr(){} + void print_me() {} // {printf(" %d ", value);} + double eval(double at); + expr *deriv(strng var); + }; + + /* an expression which is a single variable */ + class var_expr : public expr { + private: + char *name; + public: + var_expr(strng str) {strcpy(name,str);} + /* Copy the initialization string + into the name buffer. To read the documentation for + strcpy() and other C string manipulation functions, + type the Unix shell command "man string" */ + ~var_expr(){} + void print_me() {} // {printf(" %s ", name);} + double eval(double at); + expr *deriv(strng var); + }; + + /* expression resulting from applying a binary operator to two expressions */ + class bin_op_expr : public expr { + public: + bin_op_expr(expr *e1, expr *e2) {first = e1; second = e2;} + ~bin_op_expr(){} + void print_me(); + protected: + expr *first; + expr *second; + char op_name; + }; + + /* an expression which is the sum of two expressions */ + class sum_expr : public bin_op_expr { + public: + sum_expr(expr *e1, expr *e2) : bin_op_expr(e1,e2) {op_name = '+';} + ~sum_expr(){} + double eval(double at); + expr *deriv(strng var); + }; + + /* an expression which is the product of two expressions */ + class prod_expr : public bin_op_expr { + public: + prod_expr(expr *e1, expr *e2) : bin_op_expr(e1,e2) {op_name = '*';} + ~prod_expr(){} + double eval(double at); + expr *deriv(strng var); + }; + + /* an expression which is the quotient of two expressions */ + class quotient_expr : public bin_op_expr { + public: + quotient_expr(expr *e1, expr *e2) : bin_op_expr(e1,e2) {op_name = '/';} + ~quotient_expr(){} + double eval(double at); + expr *deriv(strng var); + }; From lattner at cs.uiuc.edu Mon Oct 4 15:01:29 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:29 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/README boss.h build commission.h company.h driver.cpp employee.h hourly-no-over.h hourly-over.h hourly.h piece.h wage.h Message-ID: <200410042001.PAA13241@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ: README added (r1.1) boss.h added (r1.1) build added (r1.1) commission.h added (r1.1) company.h added (r1.1) driver.cpp added (r1.1) employee.h added (r1.1) hourly-no-over.h added (r1.1) hourly-over.h added (r1.1) hourly.h added (r1.1) piece.h added (r1.1) wage.h added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+1003 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/README diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/README:1.1 *** /dev/null Mon Oct 4 15:01:24 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/README Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,8 ---- + Obtained from Bradley Kuhn, student of David Binkley, Loyola College. + The source for this program is a C++ textbook, the name is mentioned + in the following paper: + "An enabling optimization for C++ virtual functions" + by Kuhn and Binkley + in Proceedings of Mid-Atlantic States Graduate Workshop on + Programming Languages and Systems, East Stroudsburg, + PA, April 1995. Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/boss.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/boss.h:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/boss.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,96 ---- + /* boss.h -*- C++ -*- + ** Include file for Boss class + ** + ** COPYRIGHT (C) 1994 Bradley M. Kuhn + ** + ** Written : Bradley M. Kuhn Loyola College + ** By + ** + ** Written : David W. Binkley Loyola College + ** For + ** + ** Acknowledgements: + ** This code is based on code that appears in: + ** C++ How to Program by H. M. Deitel and P. J. Deitel + ** Prentice Hall, New Jersey, pp. 533-4 + ** + ** RCS : + ** + ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/boss.h,v $ + ** $Revision: 1.1 $ + ** $Date: 2004/10/04 20:01:13 $ + ** + ** $Log: boss.h,v $ + ** Revision 1.1 2004/10/04 20:01:13 lattner + ** Initial checkin of all of the source + ** + ** Revision 0.1 1994/12/24 00:35:59 bkuhn + ** # initial version + ** + ** Revision 0.1 1994/12/24 00:35:59 bkuhn + ** # initial version + ** + ** + */ + + #ifndef _BOSS_H + #define _BOSS_H + + #include "employee.h" + + #define BOSS_ID 1 + + #include + + /* A boss gets a weekly salary, regardless of how much (s)he works */ + + class Boss : public Employee { + private: + float weeklySalary; + + public: + Boss(const char *, const char * , float = 0.0); + + void SetWeeklySalary(float); + virtual float Earnings(); + virtual void Print(); + virtual void Raise(int); + virtual void NewWeek(); + }; + /*****************************************************************************/ + Boss::Boss(const char *first, const char *last, float startSalary) + : Employee(first, last) // this will call Employee's constructor + { + SetWeeklySalary(startSalary); + dollarsToRaise = 100.0; + } + /*****************************************************************************/ + void + Boss::SetWeeklySalary(float newSalary) + { + weeklySalary = (newSalary > 0.0) ? newSalary : 0.0; + } + /*****************************************************************************/ + float + Boss::Earnings() { + return weeklySalary; + } + /*****************************************************************************/ + void + Boss::Print() { + cout << " Boss: " << FirstName() << ' ' << LastName(); + } + /*****************************************************************************/ + void + Boss::Raise(int units) + { + if (units > 0) + weeklySalary += units * dollarsToRaise; + } + /*****************************************************************************/ + void + Boss::NewWeek() + { + return; + } + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/build diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/build:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/build Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,21 ---- + #!/bin/csh + + g++ -c -s driver.cc -o no.o + g++ -s driver.cc -o no + + g++ -c -s -finline-functions -O2 driver.cc -o no.inline.O2.o + g++ -s -finline-functions -O2 driver.cc -o no.inline.O2 + + g++ -c -s -finline-functions -O3 driver.cc -o no.inline.O3.o + g++ -s -finline-functions -O3 driver.cc -o no.inline.O3 + + g++ -c -s -O3 driver.cc -o no.O3.o + g++ -s -O3 driver.cc -o no.O3 + + g++ -c -s -O2 driver.cc -o no.O2.o + g++ -s -O2 driver.cc -o no.O2 + + g++ -c -s -finline-functions driver.cc -o no.inline.o + g++ -s -finline-functions driver.cc -o no.inline + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,126 ---- + /* commission.h -*- C++ -*- + ** Include file for Commission Worker class + ** + ** COPYRIGHT (C) 1994 Bradley M. Kuhn + ** + ** Written : Bradley M. Kuhn Loyola College + ** By + ** + ** Written : David W. Binkley Loyola College + ** For + ** + ** Acknowledgements: + ** This code is based on code that appears in: + ** C++ How to Program by H. M. Deitel and P. J. Deitel + ** Prentice Hall, New Jersey, pp. 534-5 + ** + ** RCS : + ** + ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h,v $ + ** $Revision: 1.1 $ + ** $Date: 2004/10/04 20:01:13 $ + ** + ** $Log: commission.h,v $ + ** Revision 1.1 2004/10/04 20:01:13 lattner + ** Initial checkin of all of the source + ** + ** Revision 0.2 1994/12/31 01:21:59 bkuhn + ** -- version were getting data from + ** + ** Revision 0.1 1994/12/28 01:36:49 bkuhn + ** # initial version + ** + ** + */ + + #ifndef _COMMISSION_H + #define _COMMISSION_H + + #include "employee.h" + + #include + #include + + #define COMMISSIONED_WORKER_ID 2 + /* A commissioned worker gets a weekly salary + commission per quantity sold */ + + class CommissionedWorker : public Employee { + private: + float weeklySalary; // base salary + float commissionRate; // % commission made on weekly sales + float thisWeekSales; // total sales this week + + protected: + void SalesThisWeek(float); + + public: + CommissionedWorker(const char *, const char * , float = 0.0, float = 0.0); + + void SetWeeklySalary(float); + void SetCommissionRate(float); + virtual float Earnings(); + virtual void Print(); + virtual void Raise(int); + virtual void NewWeek(); + }; + /*****************************************************************************/ + CommissionedWorker::CommissionedWorker(const char *first, const char *last, + float startSalary, float startCommission) + : Employee(first, last) // this will call Employee's constructor + { + SetWeeklySalary(startSalary); + SetCommissionRate(startCommission); + dollarsToRaise = 10.0; + } + /*****************************************************************************/ + void + CommissionedWorker::SetWeeklySalary(float newSalary) + { + weeklySalary = (newSalary > 0.0) ? newSalary : 0.0; + } + /*****************************************************************************/ + void + CommissionedWorker::SetCommissionRate(float newRate) + { + if (newRate < 0.0) + commissionRate = 0.0; + else if (newRate > 60.0) + commissionRate = 60.0; + else + commissionRate = newRate; + } + /*****************************************************************************/ + void + CommissionedWorker::SalesThisWeek(float sales) + { + thisWeekSales = sales; + } + /*****************************************************************************/ + float + CommissionedWorker::Earnings() { + return weeklySalary + (commissionRate / 100.0) * thisWeekSales; + } + /*****************************************************************************/ + void + CommissionedWorker::Print() { + cout << "Commissioned Worker: " << FirstName() << ' ' << LastName(); + } + /*****************************************************************************/ + void + CommissionedWorker::Raise(int units) + { + if (units > 0) { + SetCommissionRate(commissionRate + units); + weeklySalary += units * dollarsToRaise; + } + } + /*****************************************************************************/ + void + CommissionedWorker::NewWeek() + { + int quantity = 5; // rand() % 5; + + SalesThisWeek(quantity * 5000.0); + } + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,129 ---- + /* company.h -*- C++ -*- + ** Include file for a company + ** + ** COPYRIGHT (C) 1994 Bradley M. Kuhn + ** + ** Written : Bradley M. Kuhn Loyola College + ** By + ** + ** Written : David W. Binkley Loyola College + ** For + ** + ** RCS : + ** + ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h,v $ + ** $Revision: 1.1 $ + ** $Date: 2004/10/04 20:01:13 $ + ** + ** $Log: company.h,v $ + ** Revision 1.1 2004/10/04 20:01:13 lattner + ** Initial checkin of all of the source + ** + ** Revision 0.1 1994/12/24 00:39:43 bkuhn + ** # initial version + ** + ** + */ + + #ifndef _COMPANY_H + #define _COMPANY_H + + #include "employee.h" + + #include + + class EmployeeNode { + + private: + Employee * employee; + EmployeeNode * next; + + public: + EmployeeNode(Employee *, EmployeeNode *); + + Employee * Employee() { return employee; } + EmployeeNode * Next(); + }; + /*****************************************************************************/ + EmployeeNode::EmployeeNode(Employee * e, EmployeeNode * n) + { + employee = e; + next = n; + } + /*****************************************************************************/ + EmployeeNode * + EmployeeNode::Next() + { + return next; + } + /*****************************************************************************/ + + class Company { + private: + EmployeeNode * employeeList; + int employeeCount; + int currentWeek; + + public: + Company(); + + void AddEmployee(Employee *); + int EmployeeCount(); + + void PrintWithEarnings(); + void NewWeek(); + void AcrossTheBoardRaise(int); + }; + /*****************************************************************************/ + Company::Company() + { + employeeList = NULL; + employeeCount = 0; + currentWeek = 0; + } + /*****************************************************************************/ + int + Company::EmployeeCount() + { + return employeeCount; + } + /*****************************************************************************/ + void + Company::AddEmployee(Employee * e) + { + EmployeeNode * newNode; + + newNode = new EmployeeNode(e, employeeList); + employeeList = newNode; + } + /*****************************************************************************/ + void + Company::PrintWithEarnings() + { + EmployeeNode * curE; + + for(curE = employeeList; curE != NULL; curE = curE->Next()) + curE->Employee()->PrintWithEarnings(currentWeek); + } + /*****************************************************************************/ + void + Company::NewWeek() + { + EmployeeNode * curE; + + currentWeek++; + + for(curE = employeeList; curE != NULL; curE = curE->Next()) + curE->Employee()->NewWeek(); + } + /*****************************************************************************/ + void + Company::AcrossTheBoardRaise(int units) + { + EmployeeNode * curE; + + for(curE = employeeList; curE != NULL; curE = curE->Next()) + curE->Employee()->Raise(units); + } + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/driver.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/driver.cpp:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/driver.cpp Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,95 ---- + /* driver.cc -*- C++ -*- + ** Driver for the Employee Example + ** + ** COPYRIGHT (C) 1994 Bradley M. Kuhn + ** + ** Written : Bradley M. Kuhn Loyola College + ** By + ** + ** Written : David W. Binkley Loyola College + ** For + ** + ** RCS : + ** + ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/driver.cpp,v $ + ** $Revision: 1.1 $ + ** $Date: 2004/10/04 20:01:13 $ + ** + ** $Log: driver.cpp,v $ + ** Revision 1.1 2004/10/04 20:01:13 lattner + ** Initial checkin of all of the source + ** + ** Revision 0.1 1994/12/24 01:48:26 bkuhn + ** # initial version + ** + ** + */ + + #include "company.h" + #include "boss.h" + #include "commission.h" + #include "piece.h" + #include "hourly-no-over.h" + #include "hourly-over.h" + + #include + + int + main(int argc, char *argv[]) + { + int ii, totalWeeks; + int classCode; + char first[80], last[80]; + float firstArg, secondArg; + Employee * e; + Company * c; + + if (argc != 2) { + fprintf(stderr, "usage: %s \n", argv[0]); + return 1; + } + + cout << setiosflags(ios::showpoint | ios::fixed) << setprecision(2); + + totalWeeks = atoi(argv[1]); + + c = new Company(); + + while (scanf("%d%s%s%f", &classCode, first, last, &firstArg) == 4) { + switch(classCode) { + case BOSS_ID: + e = new Boss(first, last, firstArg); + break; + + case HOURLY_WORKER_NO_OVERTIME_ID: + e = new HourlyWorkerNoOvertime(first, last, firstArg); + break; + + case HOURLY_WORKER_OVERTIME_ID: + e = new HourlyWorkerOvertime(first, last, firstArg); + break; + + case PIECE_WORKER_ID: + e = new PieceWorker(first, last, firstArg); + break; + + case COMMISSIONED_WORKER_ID: + scanf("%f", &secondArg); + e = new CommissionedWorker(first, last, firstArg, secondArg); + break; + + default: + fprintf(stderr, "INVALID EMPLOYEE CODE(%d)\n", classCode); + return -1; + } + + c->AddEmployee(e); + } + + for(ii = 0; ii < totalWeeks; ii++) { + c->NewWeek(); + c->PrintWithEarnings(); + if ( (ii % 10) == 0) c->AcrossTheBoardRaise(1); + } + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/employee.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/employee.h:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/employee.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,103 ---- + /* employee.h -*- C++ -*- + ** Include file for abstract employee base class + ** + ** COPYRIGHT (C) 1994 Bradley M. Kuhn + ** + ** Written : Bradley M. Kuhn Loyola College + ** By + ** + ** Written : David W. Binkley Loyola College + ** For + ** + ** Acknowledgements: + ** This code is based on code that appears in: + ** C++ How to Program by H. M. Deitel and P. J. Deitel + ** Prentice Hall, New Jersey, pp. 531-2 + ** + ** RCS : + ** + ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/employee.h,v $ + ** $Revision: 1.1 $ + ** $Date: 2004/10/04 20:01:13 $ + ** + ** $Log: employee.h,v $ + ** Revision 1.1 2004/10/04 20:01:13 lattner + ** Initial checkin of all of the source + ** + ** Revision 0.1 1994/12/24 01:26:08 bkuhn + ** # initial version + ** + ** + */ + + #ifndef _EMPLOYEE_H + #define _EMPLOYEE_H + + #include + #include + + #define EMPLOYEE_ID 0 + + class Employee { + + private: + char * firstName; + char * lastName; + + protected: + float dollarsToRaise; // the dollar value added to salary when raised + + public: + Employee(const char *, const char *); + virtual ~Employee(); + + const char * FirstName(); + const char * LastName(); + void PrintWithEarnings(int); + + // pure virtual functions + + virtual float Earnings() = 0; + virtual void Print() = 0; + virtual void Raise(int) = 0; + virtual void NewWeek() = 0; + }; + /*****************************************************************************/ + Employee::Employee(const char * first, const char * last) + { + firstName = new char [ strlen(first) + 1 ]; + strcpy(firstName, first); + + lastName = new char [ strlen(last) + 1 ]; + strcpy(lastName, last); + } + /*****************************************************************************/ + Employee::~Employee() + { + delete [] firstName; + delete [] lastName; + } + /*****************************************************************************/ + const char * + Employee::FirstName() + { + + return firstName; // caller must make a copy + } + /*****************************************************************************/ + const char * + Employee::LastName() + { + return lastName; // caller must make a copy + } + /*****************************************************************************/ + void + Employee::PrintWithEarnings(int weekNumber) + { + this->Print(); + + cout << " earned $" << this->Earnings() << " in week " + << weekNumber << '\n'; + } + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-no-over.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-no-over.h:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-no-over.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,66 ---- + /* hourly-no-over.h -*- C++ -*- + ** Include file for Hourly No Overtime class + ** + ** COPYRIGHT (C) 1994 Bradley M. Kuhn + ** + ** Written : Bradley M. Kuhn Loyola College + ** By + ** + ** Written : David W. Binkley Loyola College + ** For + ** + ** Acknowledgements: + ** This code is based on code that appears in: + ** C++ How to Program by H. M. Deitel and P. J. Deitel + ** Prentice Hall, New Jersey, p. 536 + ** + ** RCS : + ** + ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-no-over.h,v $ + ** $Revision: 1.1 $ + ** $Date: 2004/10/04 20:01:13 $ + ** + ** $Log: hourly-no-over.h,v $ + ** Revision 1.1 2004/10/04 20:01:13 lattner + ** Initial checkin of all of the source + ** + ** Revision 0.1 1994/12/24 01:45:45 bkuhn + ** # initial version + ** + ** + */ + + #ifndef _HOURLY_NO_OVER_H + #define _HOURLY__NO_OVER_H + + #include "hourly.h" + + #include + #include + + #define HOURLY_WORKER_NO_OVERTIME_ID 7 + + /* An hourly worker no overtime gets paid for every hour worked, but no + ** extra pay is given for overtime hours */ + + class HourlyWorkerNoOvertime : public HourlyWorker { + + public: + HourlyWorkerNoOvertime(const char *, const char * , float = 0.0); + + virtual float Earnings(); + }; + /*****************************************************************************/ + HourlyWorkerNoOvertime::HourlyWorkerNoOvertime(const char *first, const char *last, + float startWage) + : HourlyWorker(first, last, startWage) // this will call Wage's constructor + { + return; + } + /*****************************************************************************/ + float + HourlyWorkerNoOvertime::Earnings() { + return Wage() * ThisWeekHours(); + } + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-over.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-over.h:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-over.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,75 ---- + /* hourly-over.h -*- C++ -*- + ** Include file for Hourly Overtime class + ** + ** COPYRIGHT (C) 1994 Bradley M. Kuhn + ** + ** Written : Bradley M. Kuhn Loyola College + ** By + ** + ** Written : David W. Binkley Loyola College + ** For + ** + ** Acknowledgements: + ** This code is based on code that appears in: + ** C++ How to Program by H. M. Deitel and P. J. Deitel + ** Prentice Hall, New Jersey, p. 537 + ** + ** RCS : + ** + ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-over.h,v $ + ** $Revision: 1.1 $ + ** $Date: 2004/10/04 20:01:13 $ + ** + ** $Log: hourly-over.h,v $ + ** Revision 1.1 2004/10/04 20:01:13 lattner + ** Initial checkin of all of the source + ** + ** Revision 0.1 1994/12/24 00:50:58 bkuhn + ** # initial version + ** + ** + */ + + #ifndef _HOURLY_OVER_H + #define _HOURLY_OVER_H + + #include "hourly.h" + + #include + #include + + #define HOURLY_WORKER_OVERTIME_ID 6 + /* An hourly worker overtime gets paid for every hour worked, and time and + ** a half for overtime hours */ + + class HourlyWorkerOvertime : public HourlyWorker { + + public: + HourlyWorkerOvertime(const char *, const char * , float = 0.0); + + virtual float Earnings(); + }; + /*****************************************************************************/ + HourlyWorkerOvertime::HourlyWorkerOvertime(const char *first, const char *last, + float startWage) + : HourlyWorker(first, last, startWage) // this will call Wage's constructor + { + return; + } + /*****************************************************************************/ + float + HourlyWorkerOvertime::Earnings() { + float totHours, overHours; + + totHours = ThisWeekHours(); + + if (totHours > 40.0) { + overHours = totHours - 40.0; + } else { + overHours = 0.0; + } + + return (Wage() * totHours) + ( (Wage() / 2.0) * overHours); + } + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly.h:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,102 ---- + /* hourly.h -*- C++ -*- + ** Include file for Hourly class + ** + ** COPYRIGHT (C) 1994 Bradley M. Kuhn + ** + ** Written : Bradley M. Kuhn Loyola College + ** By + ** + ** Written : David W. Binkley Loyola College + ** For + ** + ** Acknowledgements: + ** This code is based on code that appears in: + ** C++ How to Program by H. M. Deitel and P. J. Deitel + ** Prentice Hall, New Jersey, p. 536 + ** + ** RCS : + ** + ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly.h,v $ + ** $Revision: 1.1 $ + ** $Date: 2004/10/04 20:01:13 $ + ** + ** $Log: hourly.h,v $ + ** Revision 1.1 2004/10/04 20:01:13 lattner + ** Initial checkin of all of the source + ** + ** Revision 0.2 1994/12/31 01:22:16 bkuhn + ** -- version were getting data from + ** + ** Revision 0.1 1994/12/24 01:43:50 bkuhn + ** # initial version + ** + ** + */ + + #ifndef _HOURLY_H + #define _HOURLY_H + + #include "wage.h" + + #define HOURLY_ID 5 + #include + #include + + /* An hourly worker gets paid for every hour worked */ + + class HourlyWorker : public WageWorker { + private: + float thisWeekHours; // hours worked this week + + protected: + float ThisWeekHours() { return thisWeekHours; }; + void SetThisWeekHours(float); + + public: + HourlyWorker(const char *, const char * , float = 0.0); + + virtual void Print(); + virtual void NewWeek(); + virtual void Raise(int); + + // pure virtual function + virtual float Earnings() = 0; + }; + /*****************************************************************************/ + HourlyWorker::HourlyWorker(const char *first, const char *last, + float startWage) + : WageWorker(first, last, startWage) // this will call Wage's constructor + { + dollarsToRaise = 0.5; + thisWeekHours = 0.0; + } + /*****************************************************************************/ + void + HourlyWorker::SetThisWeekHours(float hours) + { + thisWeekHours = hours; + } + /*****************************************************************************/ + void + HourlyWorker::Print() { + cout << " Hourly Worker: " << FirstName() << ' ' << LastName(); + } + /*****************************************************************************/ + void + HourlyWorker::Raise(int units) + { + if (units > 0) + SetWage(Wage() + (units * dollarsToRaise)); + } + /*****************************************************************************/ + void + HourlyWorker::NewWeek() + { + float hours; + + hours = 44; // ( float(rand()) / float(RAND_MAX) ) * 80.0; + + SetThisWeekHours(hours); + } + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/piece.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/piece.h:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/piece.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,91 ---- + /* piece.h -*- C++ -*- + ** Include file for Piece Worker class + ** + ** COPYRIGHT (C) 1994 Bradley M. Kuhn + ** + ** Written : Bradley M. Kuhn Loyola College + ** By + ** + ** Written : David W. Binkley Loyola College + ** For + ** + ** Acknowledgements: + ** This code is based on code that appears in: + ** C++ How to Program by H. M. Deitel and P. J. Deitel + ** Prentice Hall, New Jersey, p. 536 + ** + ** RCS : + ** + ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/piece.h,v $ + ** $Revision: 1.1 $ + ** $Date: 2004/10/04 20:01:13 $ + ** + ** $Log: piece.h,v $ + ** Revision 1.1 2004/10/04 20:01:13 lattner + ** Initial checkin of all of the source + ** + ** Revision 0.2 1994/12/31 01:22:21 bkuhn + ** -- version were getting data from + ** + ** Revision 0.1 1994/12/24 00:48:37 bkuhn + ** # initial version + ** + ** + */ + + #ifndef _PIECE_H + #define _PIECE_H + + #include "wage.h" + + #define PIECE_WORKER_ID 4 + #include + + /* A piece worker gets paid for every item produced */ + + class PieceWorker : public WageWorker { + private: + int thisWeekTotal; // number of items produced + + protected: + void ProducedThisWeek(int); + + public: + PieceWorker(const char *, const char * , float = 0.0); + + virtual float Earnings(); + virtual void Print(); + virtual void NewWeek(); + }; + /*****************************************************************************/ + PieceWorker::PieceWorker(const char *first, const char *last, float startWage) + : WageWorker(first, last, startWage) + { + dollarsToRaise = 15.0; + } + /*****************************************************************************/ + void + PieceWorker::ProducedThisWeek(int total) + { + thisWeekTotal = total; + } + /*****************************************************************************/ + float + PieceWorker::Earnings() { + return Wage() * thisWeekTotal; + } + /*****************************************************************************/ + void + PieceWorker::Print() { + cout << " Piece Worker: " << FirstName() << ' ' << LastName(); + } + /*****************************************************************************/ + void + PieceWorker::NewWeek() + { + int quantity = 3; //rand() % 5; + + ProducedThisWeek(quantity); + } + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/wage.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/wage.h:1.1 *** /dev/null Mon Oct 4 15:01:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/wage.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,91 ---- + /* wage.h -*- C++ -*- + ** Include file for Wage Worker base class + ** + ** COPYRIGHT (C) 1994 Bradley M. Kuhn + ** + ** Written : Bradley M. Kuhn Loyola College + ** By + ** + ** Written : David W. Binkley Loyola College + ** For + ** + ** Acknowledgements: + ** This code is based on code that appears in: + ** C++ How to Program by H. M. Deitel and P. J. Deitel + ** Prentice Hall, New Jersey, p. 536 + ** + ** RCS : + ** + ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/wage.h,v $ + ** $Revision: 1.1 $ + ** $Date: 2004/10/04 20:01:13 $ + ** + ** $Log: wage.h,v $ + ** Revision 1.1 2004/10/04 20:01:13 lattner + ** Initial checkin of all of the source + ** + ** Revision 0.1 1994/12/24 01:45:27 bkuhn + ** # initial version + ** + ** + */ + + #ifndef _WAGE_H + #define _WAGE_H + + #include "employee.h" + + #define WAGE_WORKER_ID 3 + + #include + #include + + /* A wage worker gets paid for every (item, hour, etc) worked/produced */ + + class WageWorker : public Employee { + private: + float wage; // wage per thing + + protected: + float Wage(); + + public: + WageWorker(const char *, const char * , float = 0.0); + + void SetWage(float); + virtual void Raise(int); + + // pure virtual functions + + virtual float Earnings() = 0; + virtual void Print() = 0; + virtual void NewWeek() = 0; + }; + /*****************************************************************************/ + WageWorker::WageWorker(const char *first, const char *last, + float startWage) + : Employee(first, last) // this will call Employee's constructor + { + SetWage(startWage); + } + /*****************************************************************************/ + void + WageWorker::SetWage(float newWage) + { + wage = (newWage > 0.0) ? newWage : 0.0; + } + /*****************************************************************************/ + float + WageWorker::Wage() + { + return wage; + } + /*****************************************************************************/ + void + WageWorker::Raise(int units) + { + if (units > 0) + wage += units * dollarsToRaise; + } + + #endif From lattner at cs.uiuc.edu Mon Oct 4 15:01:28 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:28 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/README broken_light.h build check_functions.cpp check_functions.h direction.cpp direction.h intersection.cpp intersection.h light.cpp light.h main.cpp roadlet.cpp roadlet.h sim.h vehicle.cpp vehicle.h Message-ID: <200410042001.PAA13185@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/city: README added (r1.1) broken_light.h added (r1.1) build added (r1.1) check_functions.cpp added (r1.1) check_functions.h added (r1.1) direction.cpp added (r1.1) direction.h added (r1.1) intersection.cpp added (r1.1) intersection.h added (r1.1) light.cpp added (r1.1) light.h added (r1.1) main.cpp added (r1.1) roadlet.cpp added (r1.1) roadlet.h added (r1.1) sim.h added (r1.1) vehicle.cpp added (r1.1) vehicle.h added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+942 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/README diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/README:1.1 *** /dev/null Mon Oct 4 15:01:23 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/README Mon Oct 4 15:01:12 2004 *************** *** 0 **** --- 1,8 ---- + Obtained from Bradley Kuhn, student of David Binkley, Loyola College. + The source for this program is a C++ textbook, the name is mentioned + in the following paper: + "An enabling optimization for C++ virtual functions" + by Kuhn and Binkley + in Proceedings of Mid-Atlantic States Graduate Workshop on + Programming Languages and Systems, East Stroudsburg, + PA, April 1995. Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/broken_light.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/broken_light.h:1.1 *** /dev/null Mon Oct 4 15:01:26 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/broken_light.h Mon Oct 4 15:01:12 2004 *************** *** 0 **** --- 1,29 ---- + // broken_light.cc + + #ifndef _broken_light_h + #define _broken_light_h + + #include "light.h" + #include "stream.h" + extern "C" random(); + + #define BROKEN_LIGHT_ID 1 + + class broken_light : public light + { + public: + virtual int next_state(); + broken_light() : light() { __ = BROKEN_LIGHT_ID; }; + broken_light(int t1, int t2, int t3, int t4) : light (t1,t2,t3,t4){}; + }; + + inline virtual int broken_light::next_state() + { + cout << "next state called\n"; + if ((random() % 4) == 1) + return (current_state); + else + return ((current_state + 1 ) % 4); + } + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/build diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/build:1.1 *** /dev/null Mon Oct 4 15:01:26 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/build Mon Oct 4 15:01:12 2004 *************** *** 0 **** --- 1,21 ---- + #!/bin/csh + + g++ -c -s *.cc -o no.o + g++ -s *.cc -o no + + g++ -c -s -finline-functions -O2 *.cc -o no.inline.O2.o + g++ -s -finline-functions -O2 *.cc -o no.inline.O2 + + g++ -c -s -finline-functions -O3 *.cc -o no.inline.O3.o + g++ -s -finline-functions -O3 *.cc -o no.inline.O3 + + g++ -c -s -O2 *.cc -o no.O2.o + g++ -s -O2 *.cc -o no.O2 + + g++ -c -s -O3 *.cc -o no.O3.o + g++ -s -O3 *.cc -o no.O3 + + g++ -c -s -finline-functions *.cc -o no.inline.o + g++ -s -finline-functions *.cc -o no.inline + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.cpp:1.1 *** /dev/null Mon Oct 4 15:01:26 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.cpp Mon Oct 4 15:01:12 2004 *************** *** 0 **** --- 1,149 ---- + // check-functions.cc + + #include "direction.h" + #include "roadlet.h" + #include "vehicle.h" + #include "stream.h" + + + // roadlet r is the the 'd' of v->location() + + + roadlet * return_null(roadlet * r, vehicle *v, direction) + { + return(NULL); + } + + + roadlet * is_empty(roadlet *r, vehicle *v, direction d) + { + if (!r->occupied()) + return(r); + else + return(NULL); + } + + + //check both left and right. This makes sense for roads of two or fewer lanes. + roadlet * lane_switch_ok(roadlet *r, vehicle *v, direction d) + { + direction dir = v->direction(); + //cout << "dir = " << dir << "\n"; + cout << "lane switch for " << *v << " at " << *r <<'\n'; + + if (r->occupied()) + return(NULL); + + /*if ((r->neighbor(dir.right()) != NULL) && + (r->neighbor(dir.right())->occupied())) + return(NULL); + + if ((r->neighbor(dir.left()) != NULL) && + (r->neighbor(dir.left())->occupied())) + return(NULL); + don;t check right or left */ + + if ((r->neighbor(dir.back()) != NULL) && + (r->neighbor(dir.back())->occupied())) + return(NULL); + + cout << "lane switch said true \n"; + return(r); + } + + + //f from notes + roadlet * strait (roadlet *r, vehicle *v, direction d) + { + if (!r->occupied() && (v->direction() == d)) + return(r); + else + return(NULL); + + + } + + + // h from notes + roadlet * strait_or_left (roadlet *r, vehicle *v, direction d) + { + if (!r->occupied() && + ((v->direction() == d) || (v->direction().left() == d))) + return(r); + else + return(NULL); + } + + + //g from notes + roadlet * strait_or_right (roadlet *r, vehicle *v, direction d) + { + if (!r->occupied() && + ((v->direction() == d) || (v->direction().right() == d))) + return(r); + else + return(NULL); + } + + roadlet * green_light(intersection_roadlet* r, vehicle* v, direction d) + { + if ((d == N) || (d == S)) + { + if (!r->occupied() && (r->light()->greenNS())) + return(r); + else + return(NULL); + } + else + { + if (!r->occupied() && (r->light()->greenEW())) + return(r); + else + return(NULL); + } + } + + roadlet * green_OR_plan_rightONred(intersection_roadlet* r, vehicle* v, direction d) + { + int right_on_red ; + int green_light; + + cout << "green or right on red\n"; + + //if (r->light()->yellow() ) + // stop car; + + if ((d == N) || (d == S)) + { + right_on_red = (r->light()->redNS()) ; // && no on coming traffic + green_light = r->light()->greenNS(); + } + else + { + right_on_red = (r->light()->redEW()) ; // && no on coming traffic + green_light = r->light()->greenEW(); + } + + + if (right_on_red) //verify that there is a road to the right + { + if (r->neighbor(d.right()) == NULL) + { + right_on_red = FALSE; + } + else + { + v->plan = d.right().as_int(); + cout << "plan for " << *v << " is " << direction(v->plan) << "\n"; + } + } + + if (green_light) cout << "green!\n"; + if (right_on_red) cout << "right on red\n"; + if (!r->occupied() && (right_on_red || green_light)) + { + return(r); + } + else + return(NULL); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.h:1.1 *** /dev/null Mon Oct 4 15:01:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,21 ---- + // check_functions.h + + + #ifndef _check_function + #define _check_function + + #include "direction.h" + #include "roadlet.h" + #include "vehicle.h" + #include "stream.h" + + extern roadlet *return_null(roadlet*, vehicle *, direction); + extern roadlet *is_empty(roadlet *, vehicle *, direction); + extern roadlet *lane_switch_ok(roadlet *, vehicle *, direction); + extern roadlet *strait(roadlet *, vehicle *, direction); + extern roadlet *strait_or_left(roadlet *, vehicle *, direction); + extern roadlet *strait_or_right(roadlet *, vehicle *, direction); + extern roadlet *green_light(intersection_roadlet*, vehicle*, direction); + extern roadlet *green_OR_plan_rightONred(intersection_roadlet*, vehicle*, direction); + + #endif _check_function Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/direction.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/direction.cpp:1.1 *** /dev/null Mon Oct 4 15:01:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/direction.cpp Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,56 ---- + // direction.cc + + #include "direction.h" + + char *direction::as_string() + { + char *dirs[] = { "N", "NE", "E", "SE", "S", "SW", "W", "NW", + "No direction"}; + return(dirs[dir]); + } + int operator== (direction d1, direction d2) + { + return (d1.dir == d2.dir); + } + int operator!= (direction d1, direction d2) + { + return (d1.dir != d2.dir); + } + + + int operator<= (direction d1, direction d2) + { + return (d1.dir <= d2.dir); + } + + + ostream& operator<< (ostream& o, direction d) + { + o << d.as_string(); + return (o); + } + + + const direction N (0); + const direction NE(1); + const direction E (2); + const direction SE(3); + const direction S (4); + const direction SW(5); + const direction W (6); + const direction NW(7); + const direction NO_DIRECTION(8); + #ifdef direction_test + #include "stream.h" + main() + { + direction d(0); + + for(int i =0 ; i < 10; i++) + { + cout << d << ' ' << d.right() << ' ' << d.back() << ' ' << d.left() << '\n'; + d++; + } + } + #endif + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/direction.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/direction.h:1.1 *** /dev/null Mon Oct 4 15:01:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/direction.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,48 ---- + // direction.h + + #ifndef _direction_h + #define _direction_h + + #include + + class direction + { + private: + int dir; + + public: + direction() {dir = 0;}; + direction(int i) {dir = i % 9;}; + + int as_int() {return (dir);}; + char *as_string(); + direction right_front() {return(direction((dir + 1) % 8));}; + direction right() {return(direction((dir + 2) % 8));}; + direction right_back() {return(direction((dir + 3) % 8));}; + direction back() {return(direction((dir + 4) % 8));}; + direction left_back() {return(direction((dir + 5) % 8));}; + direction left() {return(direction((dir + 6) % 8));}; + direction left_front() {return(direction((dir + 7) % 8));}; + + friend ostream& operator<< (ostream&, direction); + friend int operator<= (direction d1, direction d2); + friend int operator== (direction d1, direction d2); + friend int operator!= (direction d1, direction d2); + direction operator++ () {dir++; return(*this);}; // both pre and post + }; + + + extern const direction N ; + extern const direction NE; + extern const direction E ; + extern const direction SE; + extern const direction S ; + extern const direction SW; + extern const direction W ; + extern const direction NW; + extern const direction NO_DIRECTION; + + + + typedef direction type_direction; + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.cpp:1.1 *** /dev/null Mon Oct 4 15:01:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.cpp Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,108 ---- + // build_intersection.cc + + #include "intersection.h" + extern "C" char *malloc(); + + + void intersection_4x4::connectNin (roadlet *leftlane, roadlet *rightlane) + { + connect(leftlane, S, roadlets[0][1], N, green_light); + connect(rightlane, S, roadlets[0][0], N, green_OR_plan_rightONred); + } + + void intersection_4x4::connectEin (roadlet *leftlane, roadlet *rightlane) + { + connect(leftlane, W, roadlets[1][3], E, green_light); + connect(rightlane, W, roadlets[0][3], E, green_OR_plan_rightONred); + } + + void intersection_4x4::connectSin (roadlet *leftlane, roadlet *rightlane) + { + connect(leftlane, N, roadlets[3][2], S, green_light); + connect(rightlane, N, roadlets[3][3], S, green_OR_plan_rightONred); + } + + void intersection_4x4::connectWin (roadlet *leftlane, roadlet *rightlane) + { + connect(leftlane, E, roadlets[2][0], W, green_light); + connect(rightlane, E, roadlets[3][0], W, green_OR_plan_rightONred); + } + + void intersection_4x4::connectNout(roadlet *leftlane, roadlet *rightlane) + { + connect(roadlets[0][2], N, leftlane, S, strait); + connect(roadlets[0][3], N, rightlane, S, strait_or_right); + } + void intersection_4x4::connectEout(roadlet *leftlane, roadlet *rightlane) + { + connect(roadlets[2][3], E, leftlane, W, strait); + connect(roadlets[3][3], E, rightlane, W, strait_or_right); + } + void intersection_4x4::connectSout(roadlet *leftlane, roadlet *rightlane) + { + connect(roadlets[3][1], S, leftlane, N, strait); + connect(roadlets[3][0], S, rightlane, N, strait_or_right); + } + void intersection_4x4::connectWout(roadlet *leftlane, roadlet *rightlane) + { + connect(roadlets[1][0], W, leftlane, E, strait); + connect(roadlets[0][0], W, rightlane, E, strait_or_right); + } + + + intersection_4x4::intersection_4x4(char *name) + { + char *buff; + + int i,j; + + light_type *l; + + l = new light(); + the_light = l; + + for(i=0; i<4; i++) + for(j=0; j<4; j++) + { + buff = malloc(strlen(name) + 7); + sprintf(buff, "%s %d %d", name, i, j); + roadlets[i][j] = new intersection_roadlet(buff, l); + } + + + for(i=3; i>0; i--) + { + connect(roadlets[i][3], N, roadlets[i-1][3], S, &strait); + connect(roadlets[i][2], N, roadlets[i-1][2], S, &strait); + } + for(i=0; i<3; i++) + { + connect(roadlets[i][0], S, roadlets[i+1][0], N, &strait); + connect(roadlets[i][1], S, roadlets[i+1][1], N, &strait); + } + for(j=0; j<3; j++) + { + connect(roadlets[2][j], E, roadlets[2][j+1], W, &strait); + connect(roadlets[3][j], E, roadlets[3][j+1], W, &strait); + } + for(j=3; j>0; j--) + { + connect(roadlets[0][j], W, roadlets[0][j-1], E, &strait); + connect(roadlets[1][j], W, roadlets[1][j-1], E, &strait); + } + + // override center square + // FIX ME i think car can circle forever in the middle of the intersection! + // FIX with PLAN of lefty is strait + connect(roadlets[2][2], N, roadlets[1][2], S, &strait_or_left); + connect(roadlets[1][2], W, roadlets[1][1], E, &strait_or_left); + connect(roadlets[1][1], S, roadlets[2][1], N, &strait_or_left); + connect(roadlets[2][1], E, roadlets[2][2], W, &strait_or_left); + + car b("blocker"); + b.set_location(roadlets[0][2]); // a car + roadlets[0][2]->arrive(&b); + cout << b << '\n'; + + + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.h:1.1 *** /dev/null Mon Oct 4 15:01:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,48 ---- + // build_intersection.cc + + #ifndef _intersection_h + #define _intersection_h + + #include "stdio.h" + #include "direction.h" + #include "roadlet.h" + #include "check_functions.h" + #include "light.h" + + // this function is not very OO. can that be fixed? + + + extern void connect(roadlet *, direction, + roadlet *, direction, + roadlet * (*r1_to_r2_filter_function)(roadlet *, vehicle *, direction)); + + class intersection + { + protected: + light *the_light; + public: + light *light() {return (the_light);}; + }; + + class intersection_2x2 : public intersection + { + }; + + class intersection_4x4 : public intersection + { + protected: + roadlet *roadlets[4][4]; + + public: + intersection_4x4(char *name); + void connectSin(roadlet*, roadlet*) ; + void connectNout(roadlet*, roadlet*); + void connectNin(roadlet*, roadlet*); + void connectSout(roadlet*, roadlet*); + void connectEin(roadlet*, roadlet*); + void connectWout(roadlet*, roadlet*); + void connectWin(roadlet*, roadlet*); + void connectEout(roadlet*, roadlet*); + }; + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/light.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/light.cpp:1.1 *** /dev/null Mon Oct 4 15:01:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/light.cpp Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,53 ---- + // light.cc + + #include "broken_light.h" + #include "stream.h" + + void light::tick() + { + time_remaining_in_current_state--; + if (time_remaining_in_current_state <= 0) + { + current_state = this->next_state(); + + cout << "current state = "<< current_state << '\n'; + time_remaining_in_current_state = time_in_state[current_state]; + } + } + + + + void light::init(int t1, int t2, int t3, int t4) + { + __ = LIGHT_ID; + current_state = 0; + time_in_state[0] = t1; + time_in_state[1] = t2; + time_in_state[2] = t3; + time_in_state[3] = t4; + time_remaining_in_current_state = time_in_state[current_state]; + } + + + ostream& operator<< (ostream & o, light l) + { + o << l.current_state + << " " << l.redNS() << l.yellowNS() << l.greenNS() + << " " << l.redEW() << l.yellowEW() << l.greenEW(); + return(o); + } + + #ifdef test_light + #include "stream.h" + + void main() + { + light l(3,1,4,1); + + for(int i = 0; i < 20; i++) + { + cout << l << "\n"; + l.tick(); + } + } + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/light.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/light.h:1.1 *** /dev/null Mon Oct 4 15:01:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/light.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,35 ---- + // light.h + + #ifndef _light_h + #define _light_h + #include "ostream.h" + + #define LIGHT_ID 0 + + class light + { + private: + void init(int, int, int, int); + + protected: + int current_state; + int time_in_state[4]; + int time_remaining_in_current_state; + virtual int next_state() {return ((current_state + 1 ) % 4);}; + + public: + int __; + light() {init(4,2,5,2);}; + light(int t1, int t2, int t3, int t4) {init(t1,t2,t3,t4);}; + + void tick(); + redNS() {return ((current_state == 0) || (current_state == 1));}; + yellowNS() {return (current_state == 3);}; + greenNS() {return (current_state == 2);}; + redEW() {return ((current_state == 2) || (current_state == 3));}; + yellowEW() {return (current_state == 1);}; + greenEW() {return (current_state == 0);}; + friend ostream& operator<< (ostream &, light); + }; + typedef light light_type; + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp:1.1 *** /dev/null Mon Oct 4 15:01:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,107 ---- + // main.c - simulation main driver + + #include "stream.h" + #include "sim.h" + #include "direction.h" + #include "vehicle.h" + #include "roadlet.h" + #include "check_functions.h" + #include "intersection.h" + extern "C" + { + void *malloc(); + void srandom(int); + } + + + // connect r1->d1 to r2->d2 + void connect(roadlet *r1, direction d1, + roadlet *r2, direction d2, + roadlet* (*r1_to_r2_filter_function)(roadlet *, vehicle *, direction)) + { + //cout << "connecting " << *r1 << " " << *r2 << '\n'; + r1->set_neighbor(d1, r2); + r2->set_neighbor(d2, r1); + r1->set_move_filter_function(d1, r1_to_r2_filter_function); + } + + int main() + { + car c("fred"); + roadlet *r1, *r2; + roadlet *r3, *r4; + char *buff; + int i; + + srandom(5); + + // build a two lane one direction road + + r1 = new roadlet ("R start"); + r3 = new roadlet ("L start"); + connect(r1, W, r3, E, return_null); // there but can't move to + + c.set_location(r1); // a car + r1->arrive(&c); + + for(i=0; i<10; i++) + { + buff = (char *)malloc(4); + sprintf(buff, "R%d", i); + r2 = new roadlet(buff); + + buff = (char *)malloc(4); + sprintf(buff, "L%d", i); + r4 = new roadlet(buff); + + connect(r1, N, r2, S, &is_empty); + connect(r3, N, r4, S, &is_empty); + connect(r1, NW, r4, SE, &lane_switch_ok); + connect(r3, NE, r2, SW, &lane_switch_ok); + connect(r2, W, r4, E, return_null); // can't more sideways + + r1 = r2; + r3 = r4; + } + + car b2("blocker 2"); + b2.set_location(r1); // a car + r1->arrive(&b2); + cout << b2 << '\n'; + + intersection_4x4 i1("intersection "); + + i1.connectSin(r3, r1); + + broken_light l(3,1,4,1); + + for(i = 0; i < 100000; i++) + { + cout << l << "\n"; + l.tick(); + } + + for(i=0; i< 100000; i++) + { + i1.light()->tick(); + } + + + r1 = new roadlet ("East Road R "); + r3 = new roadlet ("East Road L "); + connect(r1, N, r3, S, return_null); // there but can't move to + + car b("blocker"); + b.set_location(r1); // a car + r1->arrive(&b); + cout << b << '\n'; + + i1.connectEout(r3, r1); + + for(i=0; i< 100000; i++) + { + cout << '\n' << i << ' ' << c << '\n'; + c.tick(); + } + cout << i << ' ' << c << '\n'; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.cpp:1.1 *** /dev/null Mon Oct 4 15:01:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.cpp Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,18 ---- + // roadlet.cc + + #include + #include "roadlet.h" + + void roadlet::init(char *n) + { + name = n; + for(int i=0;i<8;i++) + the_moves[i] = return_null; + } + + + ostream& operator<<(ostream& o, roadlet r) + { + o << "roadlet " << r.name; + return (o); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h:1.1 *** /dev/null Mon Oct 4 15:01:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,55 ---- + // roadlet.h + + #ifndef _roadlet_h + #define _roadlet_h + + #include "sim.h" + #include "light.h" + extern roadlet *return_null(); + #include "check_functions.h" + #include "broken_light.h" + + typedef roadlet * (*move_function)(roadlet *, vehicle *, direction); + + + class roadlet + { + private: + void init(char *n); + + protected: + char *name; + vehicle *occupant = NULL; + roadlet *neighbors[8] = { NULL }; + move_function the_moves[8]; + + public: + roadlet() { init("unnamed");}; + roadlet(char *n) { init(n);}; + int occupied() { return(occupiedby() != NULL);}; + vehicle *occupiedby() {return(occupant);}; + void arrive(vehicle *v) {occupant = v;}; + vehicle *depart() {vehicle *v=occupant; occupant=NULL; return(v);}; + + void set_neighbor(direction d, roadlet *n) { neighbors[d.as_int()] = n;}; + roadlet *neighbor(direction d) { return(neighbors[d.as_int()]);}; + + move_function *moves() { return(the_moves);}; + void set_move_filter_function(direction d, move_function f) + {the_moves[d.as_int()] = f; }; + + friend ostream& operator<< (ostream&, roadlet); + }; + + + class intersection_roadlet : public roadlet + { + protected: + light *l; + + public: + intersection_roadlet(char *name, light *alight) : roadlet(name) {l = alight;} ; + light *light() { return(l);}; + }; + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/sim.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/sim.h:1.1 *** /dev/null Mon Oct 4 15:01:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/sim.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,21 ---- + // sim.h + + #ifndef _sim_h + #define _sim_h + + #define TRUE 1 + #define FALSE 0 + + class light; + class direction; + class roadlet; + class vehicle; + //class car : public vehicle; + class car; + // class truck : public vehicle; + class truck; + // class intersection_roadlet : public roadlet; + class intersection_roadlet; + + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.cpp:1.1 *** /dev/null Mon Oct 4 15:01:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.cpp Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,107 ---- + // vehicle.cc + // speed in (ticks per roadlet) / 100 + // speed < 100 yields multiple ticks per move. + // speed > 100 yields multiple moves per tick. + + #include + #include + #include "sim.h" + #include "direction.h" + #include "vehicle.h" + #include "roadlet.h" + + + ostream& operator<<(ostream& o, vehicle v) + { + o << v.name << " at " << *(v.location) << " going " << v.direction(); + return (o); + } + + + void vehicle::tick() + { + move_points = move_points + 100; + while (move_points >= speed) + { + move(); + move_points = move_points - speed; + } + } + + + void vehicle::move() + { + direction d = NO_DIRECTION; + + if (plan != -1) + { + cout << "there is a plan! "<< plan << " \n"; + if (location->moves()[plan](location->neighbor(plan),this,plan) != NULL) + { + d = direction(plan); + plan = -1; + } // else wait for plan to be possible + } + else + d = select_move(); + + if (d != NO_DIRECTION) + { + roadlet *r; + + location->depart(); + r = location->neighbor(d); + r->arrive(this); + location = r; + if ((d == N) || (d == S) || (d == E) || (d == W)) + dir = d; // else = lane change only + + } + } + + + direction vehicle::select_move() + { + roadlet *(**possible_moves)(roadlet*, vehicle *, type_direction); + direction dir, move_to_the[8]; + int used; + + possible_moves = location->moves(); + + for(used=0, dir=N; dir<=NW; dir ++) + { + // cout << "possible_moves[" << dir << "] " << possible_moves[dir.as_int()] << '\n'; + if (possible_moves[dir.as_int()](location->neighbor(dir), this, dir) != NULL) + { + move_to_the[used] = dir; + used++; + } + } + + if (used == 0) + { + cout << "vehicle::select_move "<< *this << " has no where to go!\n"; + return(NO_DIRECTION); + } + else + { + int use = (int)random() % used; + return(move_to_the[use]); + } + } + + + // Car stuff + ostream& operator<< (ostream& o, car c) + { + o << "Car " << (vehicle)c; + return (o); + } + + + // Truck stuff + ostream& operator<< (ostream& o, truck t) + { + o << "Truck " << (vehicle)t; + return (o); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.h:1.1 *** /dev/null Mon Oct 4 15:01:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,58 ---- + // vehicle.h + + #ifndef _vehicle_h + #define _vehicle_h + + #include "sim.h" + + class vehicle + { + private: + const int DEFAULT_SPEED = 100; + roadlet *location; + char *name; + int speed; + int move_points; // move units accumulated towards moving + void init(roadlet *l, char *n, int s) + {plan=-1,location=l, name=n, speed=s, move_points=0, dir = N;}; + + protected: + direction dir; + direction select_move(); + void move(); + + public: + vehicle() {init(NULL, NULL, DEFAULT_SPEED);}; + vehicle(char *n) {init(NULL, n, DEFAULT_SPEED);}; + vehicle(roadlet *r, char *n) {init(r, n, DEFAULT_SPEED);}; + vehicle(roadlet *r, char *n, int s) {init(r, n, s);}; + // others include: r, s, rs, sr, .... + + int plan; + + direction direction() {return (dir);}; + void set_location(roadlet *r) {location = r;}; + + void tick(); + + friend ostream& operator<< (ostream&, vehicle); + }; + + class car : public vehicle + { + public: + car() : vehicle() { }; + car(char *n) : vehicle(n) { }; + friend ostream& operator<< (ostream&, car); + }; + + class truck : public vehicle + { + protected: + int weight; + + public: + friend ostream& operator<< (ostream&, truck); + truck() { } ; // fixes moves array to be "if over weight then no else old function " + }; + #endif From lattner at cs.uiuc.edu Mon Oct 4 15:01:28 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:28 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/student3.cpp student3.h Message-ID: <200410042001.PAA13195@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2: student3.cpp added (r1.1) student3.h added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+307 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/student3.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/student3.cpp:1.1 *** /dev/null Mon Oct 4 15:01:23 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/student3.cpp Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,192 ---- + // Written for undergraduate C++ course project at Dept of + // Computer Science, Rutgers University. + #include + #include + #include "student3.h" + // evaluation of a constant is the value of the constant. + double const_expr::eval(double numb) + { + return(value); + } + // evaluation of a variable is the input value. + double var_expr::eval(double numb) + { + return(numb); + } + // evaluation of a sum expression is the sum of the values of its + // subexpressions. + double sum_expr::eval(double numb) + { + return(first->eval(numb) + second->eval(numb)); + } + // evaluation of a product expression is the product of the values of + // its subexpressions. + double prod_expr::eval(double numb) + { + return(first->eval(numb) * second->eval(numb)); + } + // evaluation of a quotient expression of the quotient + // of the values of its subexpressions. + double quotient_expr::eval(double numb) + { + return(first->eval(numb) / second->eval(numb)); + } + // An expression is printed recursively such that its left subexpression + // is printed, then the operator, then its right subexpression. + void bin_op_expr::print_me() + { + cout << "("; + first->print_me(); + cout << " " << op_name << " "; + second->print_me(); + cout << ")"; + } + // The derivative of a constant is 0. + expr *const_expr::deriv(strng var) + { + return(new const_expr(0)); + } + // The derivative of a variable is 1 if the derivative is in + // respect to the variable, and 0 otherwise. + expr *var_expr::deriv(strng var) + { + if (0/*strcmp(var, name)*/) + return(new const_expr(0)); + else + return(new const_expr(1)); + } + // The derivative of a sum expression is equal to the sum of the + // derivatives of the subexpressions. + expr *sum_expr::deriv(strng var) + { + expr *dvfirst, *dvsecond; + dvfirst = first->deriv(var); + dvsecond = second->deriv(var); + + if ((dvfirst->isconst()) && (dvfirst->eval(0) == 0)) + return(dvsecond); + else if ((dvsecond->isconst()) && (dvsecond->eval(0) == 0)) + return(dvfirst); + else + return(new sum_expr(dvfirst, dvsecond)); + } + // The derivative of a product expression is equal the the sum + // of the products of the first subexpression and the derivative of the + // second subexpression, and the second subexpression and the + // derivative of the first. + expr *prod_expr::deriv(strng var) + { + expr *dvfirst, *dvsecond; + dvfirst = first->deriv(var); + dvsecond = second->deriv(var); + + if ((dvfirst->isconst()) && (dvfirst->eval(0) == 0)) + { + if ((dvsecond->isconst()) && (dvsecond->eval(0) == 0)) + return(dvfirst); + else if ((dvsecond->isconst()) && (dvsecond->eval(0) == 1)) + return(first); + else + return(new prod_expr(first, dvsecond)); + } + else if ((dvfirst->isconst()) && (dvfirst->eval(0) ==1)) + { + if ((dvsecond->isconst()) && (dvsecond->eval(0) == 0)) + return(second); + else if ((dvsecond->isconst()) && (dvsecond->eval(0) == 1)) + return(new sum_expr(first, second)); + else + return(new sum_expr(new prod_expr(first, dvsecond), second)); + } + else + { + if ((dvsecond->isconst()) && (dvsecond->eval(0) == 0)) + return(new prod_expr(dvfirst, second)); + else if ((dvsecond->isconst()) && (dvsecond->eval(0) == 1)) + return(new sum_expr(first, new prod_expr(dvfirst, second))); + else + return(new sum_expr(new prod_expr(first, dvsecond), + new prod_expr(dvfirst, second))); + } + } + // The derivative of a quotient expression if equal to: + // (second subexpresssion * derivative of the first) - (the derivative + // of the second * the first subexpression) all over the + // second subexpression squared. + expr *quotient_expr::deriv(strng var) + { + expr *dvfirst, *dvsecond; + dvfirst = first->deriv(var); + dvsecond = second->deriv(var); + + if ((dvfirst->isconst()) && (dvfirst->eval(0) == 0)) + { + if ((dvsecond->isconst()) && (dvsecond->eval(0) == 0)) + return(dvfirst); + else if ((dvsecond->isconst()) && (dvsecond->eval(0) == 1)) + if (first->eval(0) == 1) + return(new quotient_expr(new const_expr(-1), + new prod_expr(second, second))); + else + return(new quotient_expr(new prod_expr(new const_expr(-1), first), + new prod_expr(second, second))); + else + if (first->eval(0) == 1) + return(new quotient_expr(new prod_expr(new const_expr(-1), dvsecond), + new prod_expr(second, second))); + else + return(new quotient_expr(new prod_expr(new const_expr(-1), + new prod_expr(dvsecond, first)), + new prod_expr(second, second))); + } + else if ((dvfirst->isconst()) && (dvfirst->eval(0) == 1)) + { + if ((dvsecond->isconst()) && (dvsecond->eval(0) == 0)) + return(new quotient_expr(dvfirst, second)); + else if ((dvsecond->isconst()) && (dvsecond->eval(0) == 1)) + return(new quotient_expr(new sum_expr(second, + new prod_expr(new const_expr(-1), first)), + new prod_expr(second, second))); + else + return(new quotient_expr(new sum_expr(second, + new prod_expr(new const_expr(-1),new prod_expr(dvsecond, first))), + new prod_expr(second, second))); + } + else + { + if ((dvsecond->isconst()) && (dvsecond->eval(0) == 0)) + return(new quotient_expr(dvfirst, second)); + else if ((dvsecond->isconst()) && (dvsecond->eval(0) == 1)) + return(new quotient_expr(new sum_expr(new prod_expr(second, dvfirst), + new prod_expr(new const_expr(-1),first)), + new prod_expr(second, second))); + else + return(new quotient_expr(new sum_expr(new prod_expr(second, dvfirst), + new prod_expr(new const_expr(-1), new prod_expr(dvsecond, first))), + new prod_expr(second, second))); + } + } + + main() { + const_expr c(8); + var_expr x("x"); + prod_expr simple(new const_expr(123.45), new var_expr("y")); + + cout << "c is "; + c.print_me(); + cout << "\n and its value at 3 is: " << c.eval(3); + cout << "\n and its derivative with respect to x is: "; + c.deriv("x")->print_me(); + cout << "\nx is "; + x.print_me(); + cout << "\n and its value at 3 is: " << x.eval(3); + cout << "\n and its derivative with respect to x is: "; + x.deriv("x")->print_me(); + cout << "\nsimple is "; + simple.print_me(); + cout << "\n and its value at 3 is: " << simple.eval(3); + cout << "\n and its derivative with respect to y is: "; + simple.deriv("y")->print_me(); + cout << "\n and its derivative with respect to x is: "; + simple.deriv("x")->print_me(); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/student3.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/student3.h:1.1 *** /dev/null Mon Oct 4 15:01:28 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/student3.h Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,115 ---- + // Written for undergraduate C++ course project at Dept of + // Computer Science, Rutgers University. + + //extern "C" { + // char *strcpy(char *nam, char *str); + // } + + typedef char * strng; + + /* class expr is the top of the class heirarchy for expressions. Any + expression object will be an instance of some derived class which has + class expr as its base class (or as the base class of its base class...) + */ + class expr { + public: + expr(){} + ~expr(){} + virtual void print_me() = 0; + + /* This is the function that an expression object uses to print itself. + The version given here should never be run - the print function should + be redefined in the derived class */ + + virtual expr *deriv(char *var) = 0; + /* This is the function that an expression object uses to compute its + derivative with respect to "var". The version given here should never + be run - deriv() should be redefined in the derived class */ + + virtual double eval(double at) = 0; + /* This is the function that an expression object uses to compute its + value when all variables in it are replaced by the value of "at" + */ + + virtual int isconst() = 0; + /* This is the function that can be used to determine if an expression + is a constant. */ + }; + + + /* an expression which is a numerical constant */ + class const_expr : public expr { + double value; + public: + const_expr(double v) {value = v;} + ~const_expr(){} + void print_me() {cout << " " << value << " ";} + double eval(double at); + expr *deriv(strng var); + int isconst() + { + return(1); // if the expression is a const this funtion will return true. + } + }; + + /* an expression which is a single variable */ + class var_expr : public expr { + private: + char name[30]; + public: + var_expr(strng str) {strcpy(name,str);} /* Copy the initialization string + into the name buffer. To read the documentation for + strcpy() and other C string manipulation functions, + type the Unix shell command "man string" */ + ~var_expr(){} + void print_me() {cout << " " << name << " ";} + double eval(double at); + expr *deriv(strng var); + int isconst() + { + return(0); // if the expression is a variable this functions returns false. + } + }; + + /* expression resulting from applying a binary operator to two expressions */ + class bin_op_expr : public expr { + public: + bin_op_expr(expr *e1, expr *e2) {first = e1; second = e2;} + ~bin_op_expr(){} + void print_me(); + int isconst() + { + return(0); // if the expression is a bin_op this function return false. + } + protected: + expr *first; + expr *second; + char op_name; + }; + + /* an expression which is the sum of two expressions */ + class sum_expr : public bin_op_expr { + public: + sum_expr(expr *e1, expr *e2) : bin_op_expr(e1,e2) {op_name = '+';} + ~sum_expr(){} + double eval(double at); + expr *deriv(strng var); + }; + + /* an expression which is the product of two expressions */ + class prod_expr : public bin_op_expr { + public: + prod_expr(expr *e1, expr *e2) : bin_op_expr(e1,e2) {op_name = '*';} + ~prod_expr(){} + double eval(double at); + expr *deriv(strng var); + }; + + /* an expression which is the quotient of two expressions */ + class quotient_expr : public bin_op_expr { + public: + quotient_expr(expr *e1, expr *e2) : bin_op_expr(e1,e2) {op_name = '/';} + ~quotient_expr(){} + double eval(double at); + expr *deriv(strng var); + }; From lattner at cs.uiuc.edu Mon Oct 4 15:01:28 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:28 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/family.cpp Message-ID: <200410042001.PAA13198@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/family: family.cpp added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+111 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/family.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/family.cpp:1.1 *** /dev/null Mon Oct 4 15:01:24 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/family.cpp Mon Oct 4 15:01:13 2004 *************** *** 0 **** --- 1,111 ---- + // Listings 7.1 and 7.2 from "The C++ Workbook" by Wiener and Pinson. + // Addison-Wesley 1990. + + void strcpy(char *nam1, char *nam2) {*nam1 = *nam2;} + int strlen(char *nam1) { return 0;} + + class Parent { + protected: + char *lastName; + public: + Parent(void) { + lastName = new char; // was char[5]; + strcpy(lastName, "None"); + } + + Parent (char *aLastName) { + strlen(aLastName), lastName = new char; // was char[strlen(aLastName) + 1] + strcpy(lastName,aLastName); + } + + Parent (Parent& aParent) { + strlen(aParent.lastName), lastName = new char; + strcpy(lastName,aParent.lastName); + } + + char *getLastName(void) { return lastName;} + + void setLastName(char *aName) { + strlen(aName), lastName = new char; + strcpy(lastName,aName); + } + + virtual void answerName(void) { + lastName; + } + + ~Parent(void) { + delete lastName; + } + }; + + class Child : public Parent { + protected: + char *firstName; + public: + Child(void) { + firstName = new char; + strcpy(firstName,"None"); + } + + Child (char *aLastName, char *aFirstName) : Parent (aLastName) { + strlen(aFirstName), firstName = new char; + strcpy(firstName,aFirstName); + } + + Child(Child& aChild) { + setLastName(aChild.getLastName()); + strlen(aChild.firstName), firstName = new char; + strcpy(firstName,aChild.firstName); + } + + char *getFirstName(void) { + return firstName; + } + + void setFirstName(char *aName) { + strlen(aName), firstName = new char; + strcpy(firstName,aName); + } + + ~Child(void) { + delete firstName; + } + + virtual void answerName(void) { + Parent::answerName(); + firstName; + } + }; + + class GrandChild : public Child { + private: + char *grandFatherName; + public: + GrandChild(char *aLastName,char *aFirstName,char *aGrandFatherName):Child(aLastName, + aFirstName) { + strlen(aGrandFatherName), grandFatherName = new char; + strcpy(grandFatherName, aGrandFatherName); + } + + ~GrandChild(void) { delete grandFatherName;} + + virtual void answerName(void) { + Child::answerName(); + grandFatherName; + } + }; + + main() { + Parent p("Jones"); + Child c("Jones", "Henry"); + GrandChild g("Jones", "Cynthia", "Murray"); + + Parent& f0 = p; + Parent& f1 = g; + Parent& f2 = c; + + f0.answerName(); + f1.answerName(); + f2.answerName(); + } From lattner at cs.uiuc.edu Mon Oct 4 15:01:29 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:29 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/garage/garage.cpp Message-ID: <200410042001.PAA13206@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/garage: garage.cpp added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+127 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/garage/garage.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/garage/garage.cpp:1.1 *** /dev/null Mon Oct 4 15:01:24 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/garage/garage.cpp Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,127 ---- + // Listing 4.1 page 72, from "C++ Programming Style" by + // Tom Cargill. Addison Wesley, 1992. + + #include + #include + + class Vehicle { + protected: + char *plate; + public: + Vehicle() {plate = NULL;} + Vehicle(char *p) { + plate = new char[strlen(p)+1]; + strcpy(plate,p); + } + ~Vehicle() {delete [] plate;} + virtual void identify() { + printf("generic vehicle\n"); + } + }; + + class Car : public Vehicle { + public: + Car() : Vehicle() {} + Car(char *p) : Vehicle(p) {} + void identify() { + printf("car with plate %s\n", plate); + } + }; + + class Truck : public Vehicle { + public: + Truck() : Vehicle() {} + Truck(char *p) : Vehicle(p) {} + void identify() { + printf("truck with plate %s\n", plate); + } + }; + + class Garage { + int maxVehicles; + Vehicle **parked; + public: + Garage(int max); + ~Garage(); + int accept(Vehicle *); + Vehicle *release(int bay); + void listVehicles(); + }; + + Garage::Garage(int max) { + maxVehicles = max; + parked = new Vehicle* [maxVehicles]; + for (int bay = 0; bay < maxVehicles; ++bay) + parked[bay] = NULL; + } + + Garage::~Garage() { + delete [] parked; + } + + int Garage::accept(Vehicle *veh) { + for (int bay=0; bay < maxVehicles; ++bay) + if (!parked[bay]) { + parked[bay] = veh; + return bay; + } + return -1; // no bay available + } + + Vehicle *Garage::release(int bay) { + if (bay < 0 || bay >= maxVehicles) + return NULL; + Vehicle *veh = parked[bay]; + parked[bay] = NULL; + return veh; + } + + void Garage::listVehicles() { + for (int bay=0; bay < maxVehicles; ++bay) + if (parked[bay]) { + printf("Vehicle in bay %d is: ", bay); + parked[bay]->identify(); + } + } + + Car c1("RVR 101"); + Car c2("SPT 202"); + Car c3("CHP 303"); + Car c4("BDY 404"); + Car c5("BCH 505"); + + Truck t1("TBL 606"); + Truck t2("IKY 707"); + Truck t3("FFY 808"); + Truck t4("PCS 909"); + Truck t5("SLY 000"); + + main () { + + Garage park(15); + + park.accept(&c1); + + int t2bay = park.accept(&t2); + + park.accept(&c3); + park.accept(&t1); + + int c4bay = park.accept(&c4); + + park.accept(&c5); + park.accept(&t5); + + park.release(t2bay); + + park.accept(&t4); + park.accept(&t3); + + park.release(c4bay); + + park.accept(&c2); + + park.listVehicles(); + + return 0; + } From lattner at cs.uiuc.edu Mon Oct 4 15:01:29 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:29 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/life.cpp Message-ID: <200410042001.PAA13223@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/life: life.cpp added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+181 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/life.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/life.cpp:1.1 *** /dev/null Mon Oct 4 15:01:24 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/life.cpp Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,181 ---- + // Section 9.6, "Object-Oriented Programming using C++" + // by Ira Pohl. Benjamin/Cummings Publishing Company, 1993 + + const int N=40, STATES=4; // size of square board + const int DRAB=3; + const int DFOX=8; + const int CYCLES=10; + enum state { EMPTY, GRASS, RABBIT, FOX }; + + class living; // forward decl + + typedef living *world[N][N]; // world is simulation + + class living { // what lives in world + protected: + int row, column; // location + void sums(world w, int sm[]); // sm[#states] used by next() + public: + living (int r, int c) : row(r), column(c) {} + virtual state who() = 0; // state identification + virtual living *next(world w) = 0; // compute next + }; + + void living::sums(world w, int sm[]) + { + int i,j; + sm[EMPTY] = sm[GRASS] = sm[RABBIT] = sm[FOX] = 0; + + for (i = -1; i <= 1; ++i) + for (j = -1; j <= 1; ++j) + sm[w[row+i][column+j]->who()]++; + } + + class fox : public living { + protected: + int age; + public: + fox(int r, int c, int a=0) : living(r,c), age(a) {} + state who() {return (FOX);} + living *next(world w); + }; + + class rabbit : public living { + protected: + int age; + public: + rabbit(int r, int c, int a=0) : living(r,c), age(a) {} + state who() {return (RABBIT);} + living *next(world w); + }; + + class grass : public living { + public: + grass(int r, int c) : living(r,c) {} + state who() {return (GRASS);} + living *next(world w); + }; + + class empty : public living { + public: + empty(int r, int c) : living(r,c) {} + state who() {return (EMPTY);} + living *next(world w); + }; + + + living *grass::next(world w) + { + int sum[STATES]; + sums(w, sum); + + if (sum[GRASS] > sum[RABBIT]) // eat grass + return (new grass(row, column)); + else + return (new empty(row, column)); + } + + living *rabbit::next(world w) + { + int sum[STATES]; + sums(w, sum); + + if (sum[FOX] >= sum[RABBIT]) // eat rabbits + return (new empty(row, column)); + else if (age > DRAB) // rabbit too old + return (new empty(row, column)); + else + return (new rabbit(row, column, age+1)); + } + + living *fox::next(world w) + { + int sum[STATES]; + sums(w, sum); + + if (sum[FOX] > 5) // too many foxes + return (new empty(row, column)); + else if (age > DFOX) // fox too old + return (new empty(row, column)); + else + return (new fox(row, column, age+1)); + } + + living *empty::next(world w) + { + int sum[STATES]; + sums(w, sum); + + if (sum[FOX] > 1) + return (new fox(row, column)); + else if (sum[RABBIT] > 1) // fox too old + return (new rabbit(row, column)); + else if (sum[GRASS]) + return (new grass(row, column)); + else + return (new empty(row, column)); + } + + // world is empty + void init(world w) + { + int i,j; + + for (i = 0; i < N; ++i) + for (j = 0; j < N; ++j) + w[i][j] = new empty(i,j); + } + + // new world from old world + void update(world w_new, world w_old) + { + int i,j; + + for (i = 1; i < N-1; ++i) + for (j = 1; j < N-1; ++j) + w_new[i][j] = w_old[i][j]->next(w_old); + } + + // clean world up + void dele(world w) + { + int i,j; + + for (i = 1; i < N; ++i) + for (j = 1; j < N; ++j) + delete (w[i][j]); + } + + void eden(world w) + { + int i,j; + + for (i = 1; i < N; ++i) + for (j = 1; j < N; ++j) { + if (i == j) w[i][j] = new fox(i,j); + else if (i < j) w[i][j] = new rabbit(i,j); + else w[i][j] = new grass(i,j); + } + } + + main () + { + world odd, even; + int i; + + init(odd); + init(even); + + eden(even); + + for (i = 0; i < CYCLES; ++i) { // simulation + if (i % 2) { + update(even,odd); + dele(odd); + } + else { + update(odd,even); + dele(even); + } + } + } From lattner at cs.uiuc.edu Mon Oct 4 15:01:30 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:30 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/artest.h objects.cpp onlyobj.h Message-ID: <200410042001.PAA13250@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects: artest.h added (r1.1) objects.cpp added (r1.1) onlyobj.h added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+480 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/artest.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/artest.h:1.1 *** /dev/null Mon Oct 4 15:01:24 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/artest.h Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,159 ---- + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + // Written by Ashok Sreenivasan, TRDDC, Pune, India. 1993. May be + // distributed freely, provided this comment is displayed at the top. + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + #ifndef __TBL__ + + + + #ifndef TRUE + #define TRUE (1) + #define FALSE (0) + #endif + + enum TblType + { + PERS, // For "persistent" tables + VOLAT, // For "volatile" tables + }; + + class Table : public Object + { + public: + + // Constructor + + Table (enum TblType t = PERS) : type (t) { Init (); } + + // Insertion functions + + virtual int Insert (Object *, int pos=0) = 0; + virtual int Append (Object *p) { return Insert (p, Nelem ()); } + Table &operator << (Object *p) { Append (p); return *this; } + + // Overwrite (assign) function + + virtual int Assign (Object *o, int pos = 0) + { Fetch (pos); return Insert (o, pos); } + + // Fetch functions + + virtual Object *Get (int pos) = 0; + Object *Cur () { return Get (CurInd ()); } + Object *First () { return Get (0); } + Object *Next () { return Get (CurInd()+1); } + Object *Prev () { return Get (CurInd()-1); } + Object *Last () { return Get (Nelem()-1); } + Object *operator [] (int pos) { return Get (pos); } + + // Removal functions + // Remove functions delete the object, while Fetch functions get the object + // from the table, and the table itself "forgets" the object, but it is not + // destroyed. + + virtual Object *Fetch (int pos = 0) = 0; + virtual int Remove (int pos=0) + { Object *o = Fetch (pos); delete o; return o == 0 ? 0 : 1; } + + // Search function + + virtual int Search (Object &) ; + + // Enquiry functions + + virtual int CurInd () { return curind; } + virtual int Nelem () { return nelem; } + char *Type () { return "Table"; } + enum TblType TblType () { return type; } + + // Equality Operator for tables + + int operator == (Object &o) ; + + protected: + + int nelem, curind; + enum TblType type; + void Init () { nelem = 0; curind = -1; } + }; + + class Array : public Table + { + public: + + // Constructor + + Array (int sz=100, enum TblType t = PERS); + + // Destructor + + ~Array (); + + // Insertion functions + + int Append (Object *p); + int Insert (Object *, int pos=0); + + // Overwrite (assign) function + + virtual int Assign (Object *o, int pos = 0); + + // Fetch functions + + Object *Get (int pos) ; + Object *Fetch (int pos=0); + + // Enquiry function + + int Size () { return size; } + char *Type () { return "Array"; } + + protected: + + Object **array; + int size; + }; + + class SpArray : public Array + { + public: + + // Constructor + + SpArray (int sz=100, enum TblType t = PERS) : Array (sz, t) {} + + // Destructor - use array destructor. + + ~SpArray (); + + // Overwrite (assign) function + + virtual int Assign (Object *o, int pos = 0); + + // Fetch functions + + Object *Get (int=0) ; + Object *Fetch (int=0); + + // Search function + + int Search (Object &) ; + + // Enquiry function + + char *Type () { return "SpArray"; } + int IsEmptySlot (int pos) { return ((Get (pos) == 0) ? 1 : 0); } + + private : + + // Insertion functions dont make sense for a sparse array - hence hidden away + + int Append (Object *) { return 0; } + int Insert (Object *, int=0) { return 0; } + }; + + + + #define __TBL__ + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/objects.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/objects.cpp:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/objects.cpp Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,280 ---- + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + // Written by Ashok Sreenivasan, TRDDC, Pune, India. 1993. May be + // distributed freely, provided this comment is displayed at the top. + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + #include "onlyobj.h" + int strlen(char *str1) {return 0;} + int strcmp(char *str1, char *str2) {return 0;} + char *strcpy(char *str1, char *str2) {return "";} + char *strncpy(char *str1, char *str2, int i) {return "";} + char *strcat(char *str1, char *str2) {return "";} + + #include "artest.h" + + #define abs(x) ((x) > 0 ? (x) : (-x)) + + // The search function for a table searches for the element linearly and + // returns the index of the element in the list. If not found, a -1 is + // returned. The comparison of objects is done through the '==' operator. + + int Table::Search (Object &obj) + { + for (int i = 0; i < nelem; i++) + if (obj == * (Get(i))) + return i; + return -1; + } + + // The table == operator is used to check for equality of tables themselves! + // This operator checks first if the types of the two tables are the same, + // then if the no. of elements are the same, and finally if each and every + // element is the same. Only then are the tables deemed equal. Note that + // if the tables are large, this could be an expensive operation. + + int Table::operator == (Object &tblobj) + { + char *a; + if (strcmp (a=tblobj.Type (), Type ())) // Type check + return 0; + Table *tblptr = (Table *) &tblobj; + if (tblptr->Nelem () == nelem) // Count check + { + Object *b; + for (int i = 0; i < nelem; i++) + if (*(b=tblptr->Get (i)) != *(Get(i))) // Elementwise check + return 0; + } + else + return 0; + return 1; + } + + // The array constructor allocates the reqd space and initialises the elems + // explicitly to NULL. + + Array::Array (int sz, enum TblType t) : Table (t) + { + array = new Objp [sz]; + size = sz; + for (int i = 0; i < sz; i++) // Explicitly NULLify + array [i] = 0; + } + + // The array destructor - deletes the elements from the rightmost to leftmost + // first. Once the elements are rid, the array pointer itself is deleted. + + Array::~Array () + { + if (type == VOLAT) + { + for (int i = nelem - 1; i >= 0; i--) + Remove (i); + } + + if (array) + { + delete array; + array = 0; + } + Init (); + } + + // The array append function increments nelem and sets curind and adds the + // passed element at the end. Appending to an empty array is an error. + + int Array::Append (Object *o) + { + if (nelem == size) + return 0; + array [curind = nelem] = o; + nelem ++; + return 1; + } + + // The Array insert function inserts the object at the given position and + // moves the objects to the right by one position as required. Cannot insert + // far to the right of rightmost element. Returns a boolean success / fail + // value. Insertion also fails when the array is full. + + int Array::Insert (Object *obj, int pos) + { + if (pos > nelem || pos < 0 || nelem >= size) + return 0; + for (int i = nelem; i > pos; i--) + array [i] = array [i - 1]; // Move objects right. + array [pos] = obj; + nelem ++; + curind = pos; + return 1; + } + + // The Array assign function overwrites the object at the given position with + // the passed object if the passed position is valid. + + int Array::Assign (Object *obj, int pos) + { + if (pos > nelem || pos < 0 || nelem >= size) + return 0; + if (pos == nelem) + nelem ++; // Adding new element + array [curind = pos] = obj; + return 1; + } + + // The array get function just performs a simple array access on the array + // after validating bounds. + + Object *Array::Get (int idx) + { + if (idx >= nelem || idx < 0) + return 0; + curind = idx; + return array [idx]; + } + + // The Fetch function gets an object from a list and returns it to the caller + // without deleting it. It also takes care of shifting elements + // appropriately etc. + + Object *Array::Fetch (int idx) + { + if (idx >= nelem || idx < 0) + return 0; + Object *ret = Get (idx); + for (int i = idx; i < nelem - 1; i++) + array [i] = array [i + 1]; + array [nelem - 1] = 0; + if (idx == nelem - 1) // Right most element + curind = idx - 1; + else + curind = idx; + nelem --; + return ret; + } + + // The assign function is the only way to add / overwrite elements in a + // sparse array. It just overwrites the element in the position with the new + // object, while deleting the old one if one existed. + + int SpArray::Assign (Object *o, int pos) + { + if (pos >= size || pos < 0) + return 0; + if (array [pos] == 0) + nelem ++; // increase element count + array [curind = pos] = o; + return 1; + } + + // The Get function gets the required array element and returns it. + + Object *SpArray::Get (int idx) + { + if (idx >= size || idx < 0) + return 0; + curind = idx; + return array [idx]; + } + + // The Fetch function just gets an array element and returns it, and forgets + // it from the sparse array. + + Object *SpArray::Fetch (int pos) + { + Object *ret = Get (pos); + if (ret) // Location was occupied + { + array [pos] = 0; + if (pos == nelem - 1) + curind = pos - 1; + else + curind = pos; + nelem --; + } + return ret; + } + + // Search all the elements in the array - as nelem is no limiting factor ! + + int SpArray::Search (Object &o) + { + for (int i = 0; i < size; i++) + { + Object *p = array [i]; + if (p != 0) // Location is occupied + if (*p == o) + return i; + } + return -1; + } + + // The sparse array destructor - deletes the elements from the rightmost to + // leftmost first. Once the elements are rid, the array pointer itself is + // deleted. + + SpArray::~SpArray () + { + if (type == VOLAT) + { + for (int i = size - 1; i >= 0; i--) + if (array [i] != 0) + Remove (i); + } + + if (array) + { + delete array; + array = 0; + } + Init (); + } + + class A : public Object + { + public : + int operator == (Object &o) + { char *a; + if (strcmp (a=o.Type (),Type ())) return 0; + return i == ((A&)o).i; } + char *Type () { return "A"; } + A (int j = 0) : i(j) {} + operator int () { return i; } + ~A () {} + protected : + int i; + }; + + class B : public A + { + public : + int operator == (Object &o) + { char *a; + if (strcmp (a=o.Type (),Type ())) return 0; + return j == ((B&)o).j; } + char *Type () { return "B"; } + B (int j=0) {} + operator int () { return j; } + ~B () {} + protected : + int j; + }; + + + main () + { + A *a1 = new A(1); + A *a2 = new A(2); + A *a3; + Array *ar = new Array(3,VOLAT); + SpArray *sar = new SpArray(3,VOLAT); + Array *a; + if (0) + a = ar; + else + a = sar; + a->Assign(a1); + a->Assign(a2, 2); + a3 = (A *)a->Fetch(2); + a3->Type(); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/onlyobj.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/onlyobj.h:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/onlyobj.h Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,41 ---- + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + // Written by Ashok Sreenivasan, TRDDC, Pune, India. 1993. May be + // distributed freely, provided this comment is displayed at the top. + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + #ifndef __OBJ__ + + extern "C" { + int strlen(char *str1); + int strcmp(char *str1, char *str2); + char *strcpy(char *str1, char *str2); + char *strncpy(char *str1, char *str2, int i); + char *strcat(char *str1, char *str2); + } + + class Object + { + public : + + // Constructor - Dummy, useful for breakpoints ! + + Object () {} + + // Destructor - also dummy but also virtual + + virtual ~Object () {} + + // (In)Equality operators + + virtual int operator == (Object &) = 0; + int operator != (Object &o) { return !(*this == o); } + + // Type enquiry function + + virtual char *Type () { return "Object"; } + }; + + typedef Object *Objp; + + #define __OBJ__ + #endif From lattner at cs.uiuc.edu Mon Oct 4 15:01:24 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:24 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chess.cpp chessgame.h piece.h Message-ID: <200410042001.PAA13115@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess: chess.cpp added (r1.1) chessgame.h added (r1.1) piece.h added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+403 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chess.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chess.cpp:1.1 *** /dev/null Mon Oct 4 15:01:22 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chess.cpp Mon Oct 4 15:01:12 2004 *************** *** 0 **** --- 1,211 ---- + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + // Written by Ashok Sreenivasan, TRDDC, Pune, India. 1993. May be + // distributed freely, provided this comment is displayed at the top. + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + #include "chessgame.h" + int strlen(char *str1) {return 0;} + int strcmp(char *str1, char *str2) {return 0;} + char *strcpy(char *str1, char *str2) {return "";} + char *strncpy(char *str1, char *str2, int i) {return "";} + char *strcat(char *str1, char *str2) {return "";} + int tolower(char i) {return i;} + + #define SCRATCH "scratch.gm" + Piece *star_piece, **star_star_piece; + Board::Board () + { + star_star_piece = &star_piece; + config = &star_star_piece; + config [0][0] = new Rook(CH_BLACK); + config [0][1] = new Knight(CH_BLACK); + config [0][2] = new Bishop(CH_BLACK); + config [0][3] = new Queen(CH_BLACK); + config [0][4] = new King(CH_BLACK); + config [0][5] = new Bishop(CH_BLACK); + config [0][6] = new Knight(CH_BLACK); + config [0][7] = new Rook(CH_BLACK); + config [7][0] = new Rook(CH_WHITE); + config [7][1] = new Knight(CH_WHITE); + config [7][2] = new Bishop(CH_WHITE); + config [7][3] = new Queen(CH_WHITE); + config [7][4] = new King(CH_WHITE); + config [7][5] = new Bishop(CH_WHITE); + config [7][6] = new Knight(CH_WHITE); + config [7][7] = new Rook(CH_WHITE); + for (int i=0;i<8;i++) + { + config [1][i] = new Pawn(CH_BLACK); + config [6][i] = new Pawn(CH_WHITE); + } + for (i=0;i<8;i++) + for (int j=2;j<6;j++) + config [j][i] = 0; + } + + Board :: Move (Pos *f, Pos *t) + { + config [t->x][t->y] = config [f->x][f->y]; + config [f->x][f->y] = 0; + return 0; + } + + void Board :: Dump () + { + // FILE *fp = fopen (GAMEFILE,"w"); + enum PieceType buf [64]; + int k = 0; + for (int i = 0; i < 8; i ++) + for (int j = 0; j < 8; j ++) + if (config [i][j]) + buf [k++] = config[i][j]->Rep (); + else + buf [k++] = EMPTY; + // fwrite (buf, 64, sizeof (enum PieceType), fp); + // fclose (fp); + } + + Player :: Player(char *contestant,enum Colour c) : myCol (c) + { + board = new Board; + name = new char [strlen (contestant) + 1]; + strcpy (name, contestant); + if (myCol == CH_WHITE) + board->Dump (); + PaintBoard (); + } + + Player :: Move (Pos *f, Pos *t) + { + board->Move (f, t); + board->Dump (); + PaintBoard (); + return 1; + } + + + void Player :: DumpMove (char *move) + { + // FILE *fp = fopen (MOVEFILE, "w"); + if (1 /* && !fp */) + { + // perror ("Can't open MOVE FILE"); + EndGame (); + } + // fputs (move, fp); + // fclose (fp); + } + + void Player::ProcOtherMove () + { + Pos *move = new Pos(0,0); + char str [80]; + + // FILE *fp = fopen (MOVEFILE, "r"); + if (1 /* && !fp */) + { + // perror ("Can't open MOVE FILE"); + EndGame (); + } + // fgets (str, 80, fp); + StrToMove (str, move); + board->Move (move, move); + PaintBoard (); + } + + void Player :: Play () + { + // struct stat Stat; + while (gameNotOver) + { + Pos *move = new Pos(0,0); + if (myTurn) + { + if (!firstMove) + ProcOtherMove (); + else + firstMove = 0; + GetMove (move); + Move (move, move); + if (myCol == CH_WHITE) + CreateScratch (); + // else + // unlink (SCRATCH); + SetTurn (0); + } + else + { + if (myCol == CH_BLACK) + while (/*stat(SCRATCH,&Stat) == */-1); + if (myCol == CH_WHITE) + while (/*stat(SCRATCH,&Stat) != */-1); + SetTurn (1); + } + } + } + + void Player :: PaintBoard() + { + // ::PaintBoard(myCol); + } + + void Player::GetMove (Pos *p) + { + char *move; + move = 0; /* ::GetMove(); */ + + StrToMove (move, p); + DumpMove (move); + delete move; + } + + void Player::StrToMove (char *str, Pos *p) + { + if (tolower (str [0]) == 'q') + { + DumpMove ("q"); + if (myCol == CH_WHITE) + CreateScratch (); + // else + // unlink (SCRATCH); + EndGame (); + } + p[0].x = 8 - (str[1] - '0'); + p[0].y = str[0] - 'a'; + p[1].x = 8 - (str[4] - '0'); + p[1].y = str[3] - 'a'; + } + + void Player :: CreateScratch () + { + // FILE *fp = fopen (SCRATCH, "w"); + // fclose (fp); + } + + #define STARTFILE "start.gm" + + char gameNotOver = 1; + char firstMove = 0; + + main () + { + // struct stat Stat; + // FILE *fp; + Player *player; + + if (/*stat(STARTFILE,&Stat) == */-1) + { + // fp = fopen(STARTFILE,"w"); + // fclose(fp); + player = new Player("white",CH_WHITE); + firstMove = 1; + player->SetTurn (1); + } + else + { + // unlink(STARTFILE); + player = new Player("black",CH_BLACK); + player->SetTurn (0); + } + player->Play (); + EndGame (); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chessgame.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chessgame.h:1.1 *** /dev/null Mon Oct 4 15:01:24 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chessgame.h Mon Oct 4 15:01:12 2004 *************** *** 0 **** --- 1,153 ---- + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + // Written by Ashok Sreenivasan, TRDDC, Pune, India. 1993. May be + // distributed freely, provided this comment is displayed at the top. + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + #ifndef __CHESS__ + + #define __CHESS__ + + #include "piece.h" + + #define GAMEFILE "chess.gm" + #define MOVEFILE "move.gm" + + enum Colour + { + CH_WHITE, + CH_BLACK, + }; + + class Board; + class Player; + + class Pos + { + public : + + Pos (int a = 0, int b = 0) : x (a), y (b) {} + // friend class Board; + // friend class Player; + + // private : + + int x, y; + }; + + class Piece + { + public : + + Piece (enum Colour c) : myCol (c) {} + virtual int Validate (Board *, Pos *, Pos *) = 0; + virtual enum PieceType Rep () = 0; + enum Colour myCol; + }; + + class Board + { + public : + + Board (); + int Move (Pos *from, Pos *to); + void Dump (); + void Retrieve (); + int Undo (); + ~Board (); + + private : + + Piece ***config/* [8][8]*/; + }; + + class Pawn : public Piece + { + public : + + Pawn (enum Colour c) : Piece (c) {} + int Validate (Board *, Pos *, Pos *){return 1;} + enum PieceType Rep () + { if (myCol == CH_WHITE) return WPAWN; else return BPAWN; }; + }; + + class Rook : public Piece + { + public : + + Rook (enum Colour c) : Piece (c) {} + int Validate (Board *, Pos *, Pos *) {return 1;} + enum PieceType Rep () + { if (myCol == CH_WHITE) return WROOK; else return BROOK; }; + }; + + class Knight : public Piece + { + public : + + Knight (enum Colour c) : Piece (c) {} + int Validate (Board *, Pos *, Pos *){return 1;} + enum PieceType Rep () + { if (myCol == CH_WHITE) return WKNIGHT; else return BKNIGHT; }; + }; + + class Bishop : public Piece + { + public : + + Bishop (enum Colour c) : Piece (c) {} + int Validate (Board *, Pos *, Pos *){return 1;} + enum PieceType Rep () + { if (myCol == CH_WHITE) return WBISHOP; else return BBISHOP; }; + }; + + class Queen : public Piece + { + public : + + Queen (enum Colour c) : Piece (c) {} + int Validate (Board *, Pos *, Pos *){return 1;} + enum PieceType Rep () + { if (myCol == CH_WHITE) return WQUEEN; else return BQUEEN; }; + }; + + class King : public Piece + { + public : + + King (enum Colour c) : Piece (c) {} + int Validate (Board *, Pos *, Pos *){return 1;} + enum PieceType Rep () + { if (myCol == CH_WHITE) return WKING; else return BKING; }; + }; + + class Player + { + public : + + Player (char *, enum Colour c = CH_WHITE); + int Move (Pos *, Pos *); + int Undo (); + int Resign (); + void PaintBoard(); + void SetTurn (char i) { myTurn = i; } + void Play (); + + private : + + char *name; + Board *board; + enum Colour myCol; + char myTurn; + + void StrToMove (char *, Pos *); + void GetMove (Pos *); + void ProcOtherMove (); + void DumpMove (char *); + void CreateScratch (); + }; + + extern char gameNotOver; + extern char firstMove; + + void EndGame () {} + + #endif /* __CHESS__ */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/piece.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/piece.h:1.1 *** /dev/null Mon Oct 4 15:01:24 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/piece.h Mon Oct 4 15:01:12 2004 *************** *** 0 **** --- 1,39 ---- + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + // Written by Ashok Sreenivasan, TRDDC, Pune, India. 1993. May be + // distributed freely, provided this comment is displayed at the top. + // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + #ifndef __PIECE__ + extern "C" { + int strlen(char *str1); + int strcmp(char *str1, char *str2); + char *strcpy(char *str1, char *str2); + char *strncpy(char *str1, char *str2, int i); + char *strcat(char *str1, char *str2); + } + + enum PieceType + { + WPAWN, + BPAWN, + WROOK, + BROOK, + WKNIGHT, + BKNIGHT, + WBISHOP, + BBISHOP, + WQUEEN, + BQUEEN, + WKING, + BKING, + EMPTY, + UNKNOWN, + }; + + #define ISWHITE(p) (p == WPAWN || p == WROOK || p == WKNIGHT || \ + p == WBISHOP || p == WQUEEN || p == WKING) + + #define ISBLACK (P) (!ISWHITE(p) && p != EMPTY && p != UNKNOWN) + + #define __PIECE__ + + #endif From lattner at cs.uiuc.edu Mon Oct 4 15:01:30 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:30 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/README office.cpp person.h supervsr.h Message-ID: <200410042001.PAA13285@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/office: README added (r1.1) office.cpp added (r1.1) person.h added (r1.1) supervsr.h added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+217 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/README diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/README:1.1 *** /dev/null Mon Oct 4 15:01:25 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/README Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,3 ---- + Obtained from the C++ tutorial notes Steve Masticola had + on Rutgers machine. Appears to be from Chapter 11 of some + unknown book! : Hemant Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/office.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/office.cpp:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/office.cpp Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,151 ---- + // Chapter 11 - Program 4 + #include + #include "supervsr.h" + + // In all cases, init_data assigns values to the class variables and + // display outputs the values to the monitor for inspection. + + supervisor::supervisor(char *in_name, int in_salary, char *in_title) + { + name = in_name; + salary = in_salary; + title= in_title; + } + + + + + void + supervisor::display(void) + { + cout << "Supervisor --> " << name << "'s salary is " << salary << + " and is the " << title << ".\n\n"; + } + + + + + programmer::programmer(char *in_name, int in_salary, char *in_title, + char *in_language) + { + name = in_name; + salary = in_salary; + title = in_title; + language = in_language; + } + + + + + void + programmer::display(void) + { + cout << "Programmer --> " << name << "'s salary is " << salary << + " and is " << title << ".\n"; + cout << " " << name << "'s specialty is " << + language << ".\n\n"; + } + + + + + secretary::secretary(char *in_name, int in_salary, + int in_shorthand, int in_typing_speed) + { + name = in_name; + salary = in_salary; + shorthand = in_shorthand; + typing_speed = in_typing_speed; + } + + + + + void + secretary::display(void) + { + cout << "Secretary ---> " << name << "'s salary is " << salary << + ".\n"; + cout << " " << name << " types " << typing_speed << + " per minute and can "; + if (!shorthand) cout << "not "; + cout << "take shorthand.\n\n"; + } + + consultant::consultant(char *in_name, + int in_salary, + char *in_specialty, + int in_contract_length) + { + name = in_name; + salary = in_salary; + specialty = in_specialty; + contract_length = in_contract_length; + } + + + + + void + consultant::display(void) + { + cout << "Consultant --> " << name << "'s salary is " << salary << + " and consults in " << + specialty << ".\n"; + cout << " " << name << "'s contract lasts " << + contract_length << + " weeks.\n\n"; + } + + // Chapter 11 - Program 5 + + person *staff1,*staff2,*staff3,*staff4; + + main() + { + supervisor *suppt; + programmer *progpt; + secretary *secpt; + + suppt = new supervisor("Big John", 5100, "President"); + staff1 = suppt; + + progpt = new programmer("Joe Hacker", 3500, "debugger", "Pascal"); + staff2 = progpt; + + progpt = new programmer("OOP Wizard", 7700, "senior analyst", "C++"); + staff3 = progpt; + + secpt = new secretary("Tillie Typer", 2200, 1, 85); + staff4 = secpt; + + staff1->display(); + staff2->display(); + staff3->display(); + staff4->display(); + } + + + + + // Result of execution + + // XYZ Staff -- note salary is monthly. + // + // Supervisor --> Big John's salary is 5100 and is the President. + // + // Programmer --> Joe Hacker's salary is 3500 and is debugger. + // Joe Hacker's specialty is Pascal. + // + // Programmer --> OOP Wizard's salary is 7700 and is senior analyst. + // OOP Wizard's specialty is C++. + // + // Secretary ---> Tillie Typer's salary is 2200. + // Tillie typer types 85 per minute and can take shorthand. + // + // Supervisor --> Tom Talker's salary is 5430 and is the sales manager. + // + // Programmer --> Dave Debugger's salary is 5725 and is code maintainer. + // Dave Debugger's specialty is assembly language. + // + // End of employee list. Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/person.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/person.h:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/person.h Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,14 ---- + // Chapter 11 - Program 1 + #ifndef PERSON_H + #define PERSON_H + + class person { + protected: // Make these variables available to the subclasses + char *name; + int salary; + public: + person(void) {} + virtual void display(void) = 0; + }; + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/supervsr.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/supervsr.h:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/supervsr.h Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,49 ---- + // Chapter 11 - Program 3 + #ifndef SUPERVSR_H + #define SUPERVSR_H + + // This defines three subclasses of the parent type person. Different + // data is stored for the different job classifications to illustrate + // that it can be done. + + #include "person.h" + + class supervisor : public person { + char *title; + public: + supervisor(char *in_name, int in_salary, char *in_title); + void display(void); + }; + + + + class programmer : public person { + char *title; + char *language; + public: + programmer(char *in_name, int in_salary, char *in_title, + char *in_language); + void display(void); + }; + + + + class secretary : public person { + char shorthand; + int typing_speed; + public: + secretary(char *in_name, int in_salary, + int in_shorthand, int in_typing_speed); + void display(void); + }; + + class consultant : public person { + char *specialty; + int contract_length; + public: + consultant(char *in_name, int in_salary, + char *in_specialty, int in_contract_length); + void display(void); + }; + + #endif From lattner at cs.uiuc.edu Mon Oct 4 15:01:30 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:30 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/README cell.hh constants.hh coordinate.hh obstacle.hh ocean.cpp ocean.hh predator.hh prey.hh random.hh Message-ID: <200410042001.PAA13293@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean: README added (r1.1) cell.hh added (r1.1) constants.hh added (r1.1) coordinate.hh added (r1.1) obstacle.hh added (r1.1) ocean.cpp added (r1.1) ocean.hh added (r1.1) predator.hh added (r1.1) prey.hh added (r1.1) random.hh added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+446 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/README diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/README:1.1 *** /dev/null Mon Oct 4 15:01:24 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/README Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,2 ---- + Listings 8.1 to 8.14. "The C++ Workbook" by Wiener and Pinson, + Addison-Wesley, 1990. Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/cell.hh diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/cell.hh:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/cell.hh Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,36 ---- + #ifndef CellDef + #define CellDef + + class Cell { + friend class Ocean; + + protected: + Coordinate *offset; + char image; + + Cell *getCellAt(Coordinate aCoord); + void assignCellAt(Coordinate aCoord, Cell *aCell); + Cell *getNeighborWithImage(char anImage); + Coordinate getEmptyNeighborCoord(void); + Coordinate getPreyNeighborCoord(void); + Cell *north(void); + Cell *south(void); + Cell *east(void); + Cell *west(void); + virtual Cell *reproduce(Coordinate anOffset); + + public: + Cell(Coordinate &aCoord) { + offset = new Coordinate(aCoord); + image = DefaultImage; + } + Cell(void) {} + virtual ~Cell(void) {delete offset;} + Coordinate &getOffset(void) {return *offset;} + void setOffset(Coordinate &anOffset) {offset = new Coordinate(anOffset);} + char getImage(void) { return image;} + void display(void); + virtual void process(void) {} + }; + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/constants.hh diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/constants.hh:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/constants.hh Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,21 ---- + #ifndef Constants + #define Constants + + #define MaxRows 25 + #define MaxCols 70 + + #define DefaultNumObstacles 75 + #define DefaultNumPredators 20 + #define DefaultNumPrey 150 + + #define DefaultNumIterations 1000 + + #define DefaultImage '-' + #define DefaultPreyImage 'f' + #define DefaultPredImage 'S' + #define ObstacleImage '#' + + #define TimeToFeed 6 + #define TimeToReproduce 6 + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/coordinate.hh diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/coordinate.hh:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/coordinate.hh Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,33 ---- + #ifndef CoordinateDef + #define CoordinateDef + + class Coordinate { + private: + unsigned x; + unsigned y; + + public: + Coordinate(unsigned anX, unsigned aY) : x(anX), y(aY) {} + Coordinate(Coordinate &aCoord) { + x = aCoord.x; + y = aCoord.y; + } + Coordinate(void) {} + ~Coordinate(void) {} + unsigned getX(void) {return x;} + unsigned getY(void) {return y;} + void setX(unsigned anX) {x = anX;} + void setY(unsigned aY) {y = aY;} + void operator = (Coordinate &aCoord) { + x = aCoord.x; + y = aCoord.y; + } + int operator == (Coordinate &c) { + return (x == c.x && y == c.y); + } + int operator != (Coordinate &c) { + return (x != c.x && y != c.y); + } + }; + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/obstacle.hh diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/obstacle.hh:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/obstacle.hh Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,12 ---- + #ifndef ObstacleDef + #define ObstacleDef + + class Obstacle : public Cell { + public: + Obstacle(Coordinate &aCoord) : Cell(aCoord) { + image = ObstacleImage; + } + virtual ~Obstacle(void) {Cell::~Cell();} + }; + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.cpp:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.cpp Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,236 ---- + #include "constants.hh" + #include "random.hh" + #include "coordinate.hh" + #include "ocean.hh" + #include "cell.hh" + #include "prey.hh" + #include "predator.hh" + #include "obstacle.hh" + + //cell.cc + Cell *Cell::getCellAt(Coordinate aCoord) { + return cells[aCoord.getY()][aCoord.getX()]; + } + + void Cell::assignCellAt(Coordinate aCoord, Cell *aCell) { + cells[aCoord.getY()][aCoord.getX()] = aCell; + } + + Cell *Cell::getNeighborWithImage(char anImage) { + Cell *neighbors[4]; + unsigned count = 0; + if (north()->getImage() == anImage) neighbors[count++] = north(); + if (south()->getImage() == anImage) neighbors[count++] = south(); + if (east()->getImage() == anImage) neighbors[count++] = east(); + if (west()->getImage() == anImage) neighbors[count++] = west(); + if (!count) return this; + else + return neighbors[Ocean1->random->nextIntBetween(0,count-1)]; + } + + Coordinate Cell::getEmptyNeighborCoord(void) { + return getNeighborWithImage(DefaultImage)->getOffset(); + } + + Coordinate Cell::getPreyNeighborCoord(void) { + return getNeighborWithImage(DefaultPreyImage)->getOffset(); + } + + Cell *Cell::north(void) { + unsigned yvalue; + yvalue = (offset->getY() > 0) ? (offset->getY()-1) : (Ocean1->numRows-1); + return cells[yvalue][offset->getX()]; + } + + Cell *Cell::south(void) { + unsigned yvalue; + yvalue = (offset->getY()+1) % Ocean1->numRows; + return cells[yvalue][offset->getX()]; + } + + Cell *Cell::east(void) { + unsigned xvalue; + xvalue = (offset->getX()+1) % Ocean1->numCols; + return cells[offset->getY()][xvalue]; + } + + Cell *Cell::west(void) { + unsigned xvalue; + xvalue = (offset->getX() > 0) ? (offset->getX()-1) : (Ocean1->numCols-1); + return cells[offset->getY()][xvalue]; + } + + Cell *Cell::reproduce(Coordinate anOffset) { + Cell *temp = new Cell(anOffset); + return temp; + } + + void Cell::display(void) {} + + //prey.cc + void Prey::moveFrom(Coordinate from, Coordinate to) { + Cell *toCell; + --timeToReproduce; + if (to != from) { + toCell = getCellAt(to); + delete toCell; + setOffset(to); + assignCellAt(to, this); + if (timeToReproduce <= 0) { + timeToReproduce = TimeToReproduce; + assignCellAt(from, reproduce(from)); + } + else + assignCellAt(from, new Cell(from)); + } + } + + Cell *Prey::reproduce(Coordinate anOffset) { + Prey *temp = new Prey(anOffset); + Ocean1->setNumPrey(Ocean1->getNumPrey()+1); + return (Cell *) temp; + } + + //predator.cc + void Predator::process(void) { + Coordinate toCoord; + if (--timeToFeed <= 0) { + assignCellAt(*offset, new Cell(*offset)); + Ocean1->setNumPredators(Ocean1->getNumPredators()-1); + delete this; + } + else { + toCoord = getPreyNeighborCoord(); + if (toCoord != *offset) { + Ocean1->setNumPrey(Ocean1->getNumPrey()-1); + timeToFeed = TimeToFeed; + moveFrom(*offset, toCoord); + } + else + Prey::process(); + } + } + + Cell *Predator::reproduce(Coordinate anOffset) { + Predator *temp = new Predator(anOffset); + Ocean1->setNumPredators(Ocean1->getNumPredators()+1); + return (Cell *) temp; + } + + //random.cc + #define MAX 32767 + + float Random::randReal(void) { + return 0.0; + } + + unsigned Random::nextIntBetween(int low, int high) { + return 0; + } + + //ocean.cc + void Ocean::initialize(void) { + random = new Random(); + random->initialize(); + numRows = MaxRows; + numCols = MaxCols; + + numObstacles = DefaultNumObstacles; + numPredators = DefaultNumPredators; + numPrey = DefaultNumPrey; + + initCells(); + } + + void Ocean::initCells(void) { + addEmptyCells(); + if (numPredators == (size - numObstacles)) + numPredators = size - numObstacles; + if (numPrey == (size - numObstacles - numPredators)) + numPrey = size - numObstacles - numPredators; + addObstacles(); + addPredators(); + addPrey(); + displayStats(-1); + displayBorder(); + Ocean1 = this; + } + + void Ocean::addEmptyCells(void) { + for (unsigned row = 0; row < numRows; row++) + for (unsigned col = 0; col < numCols; col++) + cells[row][col] = new Cell(Coordinate(col,row)); + } + + void Ocean::addObstacles(void) { + Coordinate empty; + for (unsigned count = 0; count < numObstacles; count++) { + empty = getEmptyCellCoord(); + cells[empty.getY()][empty.getX()] = new Obstacle(empty); + } + } + + void Ocean::addPredators(void) { + Coordinate empty; + for (unsigned count = 0; count < numPredators; count++) { + empty = getEmptyCellCoord(); + cells[empty.getY()][empty.getX()] = new Predator(empty); + } + } + + void Ocean::addPrey(void) { + Coordinate empty; + for (unsigned count = 0; count < numPredators; count++) { + empty = getEmptyCellCoord(); + cells[empty.getY()][empty.getX()] = new Prey(empty); + } + } + + Coordinate Ocean::getEmptyCellCoord(void) { + unsigned x, y; + Coordinate empty; + do { + x = random->nextIntBetween(0,numCols-1); + y = random->nextIntBetween(0,numRows-1); + } + while (cells[y][x]->getImage() != DefaultImage); + empty = cells[y][x]->getOffset(); + delete cells[y][x]; + return empty; + } + + void Ocean::displayBorder(void) { + for (unsigned col = 0; col < numCols; col++); + } + + void Ocean::displayCells(void) { + for (unsigned row = 0; row < numRows; row++) + for (unsigned col = 0; col < numCols; col++) + cells[row][col]->display(); + } + + void Ocean::displayStats(int iteration) { + // lots of cout stuff + displayBorder(); + } + + void Ocean::run(void) { + unsigned numIterations = DefaultNumIterations; // instead of cin + if (numIterations > 1000) numIterations = DefaultNumIterations; + for (unsigned iteration = 0; iteration < numIterations; iteration++) { + if (numPredators > 0 && numPrey > 0) { + for (unsigned row = 0; row < numRows; row++) + for (unsigned col = 0; col < numCols; col++) + cells[row][col]->process(); + displayStats(iteration); + displayCells(); + displayBorder(); + } + } + } + + main() { + Ocean *myOcean = new Ocean; + myOcean->initialize(); + myOcean->run(); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.hh diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.hh:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.hh Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,41 ---- + #ifndef OceanDef + #define OceanDef + + class Cell; + Cell *cells[MaxRows][MaxCols]; + + class Ocean { + friend class Cell; + private: + unsigned numRows; + unsigned numCols; + unsigned size; + unsigned numPrey; + unsigned numPredators; + unsigned numObstacles; + Random *random; + + void initCells(void); + void addEmptyCells(void); + void addObstacles(void); + void addPredators(void); + void addPrey(void); + Coordinate getEmptyCellCoord(void); + void displayBorder(void); + void displayCells(void); + void displayStats(int iteration); + + public: + unsigned getNumPrey(void) {return numPrey;} + unsigned getNumPredators(void) {return numPredators;} + void setNumPrey(unsigned aNumber) {numPrey = aNumber;} + void setNumPredators(unsigned aNumber) {numPredators = aNumber;} + void initialize(void); + void run(void); + Ocean(void) {} + ~Ocean(void) {delete random;} + }; + + Ocean *Ocean1; + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/predator.hh diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/predator.hh:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/predator.hh Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,20 ---- + #ifndef PredatorDef + #define PredatorDef + + class Predator : public Prey { + private: + virtual Cell *reproduce(Coordinate anOffset); + + protected: + unsigned timeToFeed; + + public: + Predator(Coordinate aCoord) : Prey(aCoord) { + timeToFeed = TimeToFeed; + image = DefaultPredImage; + } + virtual ~Predator(void) {Prey::~Prey();} + virtual void process(void); + }; + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/prey.hh diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/prey.hh:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/prey.hh Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,25 ---- + #ifndef PreyDef + #define PreyDef + + class Prey : public Cell { + protected: + int timeToReproduce; + + void moveFrom(Coordinate from, Coordinate to); + Cell *reproduce(Coordinate anOffset); + + public: + Prey(Coordinate &aCoord) : Cell(aCoord) { + timeToReproduce = TimeToReproduce; + image = DefaultPreyImage; + } + ~Prey(void) {Cell::~Cell();} + void process(void) { + Coordinate toCoord; + + toCoord = getEmptyNeighborCoord(); + moveFrom(*offset,toCoord); + } + }; + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/random.hh diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/random.hh:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/random.hh Mon Oct 4 15:01:14 2004 *************** *** 0 **** --- 1,20 ---- + #ifndef RandomDef + #define RandomDef + + class Random { + private: + int seed1, seed2; + public: + void initialize(void) { + seed1 = 3797; + seed2 = 2117; + } + void init(int s1, int s2) { + seed1 = s1; + seed2 = s2; + } + float randReal(void); + unsigned nextIntBetween(int low, int high); + }; + + #endif From lattner at cs.uiuc.edu Mon Oct 4 15:01:30 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:30 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/primes.cpp Message-ID: <200410042001.PAA13256@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes: primes.cpp added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+48 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/primes.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/primes.cpp:1.1 *** /dev/null Mon Oct 4 15:01:25 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/primes.cpp Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,48 ---- + // From Ravi Sethi's book on Programming Languages. + + #include + class item { + public: + item *source; + item(item *src) {source = src;} + virtual int out() {return 0;} + }; + class counter : public item { + int value; + public: + int out() {return value++;} + counter(int v) : item(0) {value = v;} + }; + class sieve : public item { + public: + int out(); + sieve(item *src) : item(src) {}; + }; + class filter : public item { + int factor; + public: + int out(); + filter(item *src, int f) : item (src) {factor = f;} + }; + main() { + counter c(2); + sieve s(&c); + int next; + do { + next = s.out(); + printf("%d ",next); + } while (next < 61); + printf ("\n"); + } + int sieve::out() { + int n = source->out(); + source = new filter(source,n); + return n; + } + int filter::out() { + while (1) { + int n = source->out(); + if (n % factor) + return n; + } + } From lattner at cs.uiuc.edu Mon Oct 4 15:01:30 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:30 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/vcirc.cpp vpoint.h Message-ID: <200410042001.PAA13290@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc: vcirc.cpp added (r1.1) vpoint.h added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+142 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/vcirc.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/vcirc.cpp:1.1 *** /dev/null Mon Oct 4 15:01:25 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/vcirc.cpp Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,105 ---- + // Borland C++ + + /* VPOINT.CPP--Example from Getting Started */ + + // VPOINT.CPP contains the definitions for the Point and Location + // classes that are declared in the file vpoint.h + + #include "vpoint.h" + + // member functions for the Location class + + Location::Location(int InitX, int InitY) { + X = InitX; + Y = InitY; + } + + int Location::GetX() { + return X; + } + + int Location::GetY() { + return Y; + } + + // member functions for the Point class: These assume + // the main program has initialized the graphics system + + void Point::Show() { + Visible = True; + // putpixel(X, Y, getcolor()); uses default color + } + + void Point::Hide(void) { + Visible = False; + // putpixel(X, Y, getbkcolor()); uses background color to erase + } + + Boolean Point::IsVisible() { + return Visible; + } + + void Point::MoveTo(int NewX, int NewY) { + Hide(); // make current point invisible + X = NewX; // change X and Y coordinates to new location + Y = NewY; + Show(); // show point at new location + } + + // A Circle class derived from Point + + class Circle : public Point { + int Radius; // private by default + + public: + Circle(int InitX, int InitY, int InitRadius) : Point(InitX,InitY) { + Radius = InitRadius; + } + void Show(void); + void Hide(void); + void Expand(int ExpandBy); + void Contract(int ContractBy); + }; + + void Circle::Show() + { + Visible = True; + // circle(X, Y, Radius); draw the circle using BGI function + } + + void Circle::Hide() + { + if (!Visible) return; // no need to hide + unsigned int TempColor; // to save current color + // TempColor = getcolor(); set to current color + // setcolor(getbkcolor()); set drawing color to background + Visible = False; + // circle(X, Y, Radius); draw in background color to erase + // setcolor(TempColor); set color back to current color + } + + void Circle::Expand(int ExpandBy) + { + Boolean vis = Visible; // is current circle visible? + if (vis) Hide(); // if so, hide it + Radius += ExpandBy; // expand radius + if (Radius < 0) // avoid negative radius + Radius = 0; + if (vis) Show(); // draw new circle if previously visible + } + + inline void Circle::Contract(int ContractBy) + { + Expand(-ContractBy); // redraws with (Radius - ContractBy) + } + + main() // test the functions + { + Circle MyCircle(50, 100, 25); // declare a circle object + MyCircle.Show(); // show it + MyCircle.MoveTo(100, 125); // move the circle (tests hide + // and show also) + MyCircle.Expand(25); // make it bigger + MyCircle.Contract(35); // make it smaller + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/vpoint.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/vpoint.h:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/vpoint.h Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,37 ---- + // Borland C++ + + /* vpoint.h--Example from Getting Started */ + + // version of point.h with virtual functions for use with VCIRCLE + // vpoint.h contains two classes: + // class Location describes screen locations in X and Y coordinates + // class Point describes whether a point is hidden or visible + + enum Boolean { False, True }; + + class Location { + protected: // allows derived class to access private data + int X; + int Y; + + public: // these functions can be accessed from outside + Location(int InitX, int InitY); + int GetX(void); + int GetY(void); + }; + + class Point : public Location { // derived from class Location + // public derivation means that X and Y are protected within Point + + protected: + Boolean Visible; // classes derived from Point will need access + + public: + Point(int InitX, int InitY) : Location(InitX,InitY) { // constructor + Visible = False; // make invisible by default + } + virtual void Show(void); + virtual void Hide(void); + Boolean IsVisible(void); + void MoveTo(int NewX, int NewY); + }; From lattner at cs.uiuc.edu Mon Oct 4 15:01:30 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:30 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/README tree.cpp tree.h Message-ID: <200410042001.PAA13296@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees: README added (r1.1) tree.cpp added (r1.1) tree.h added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+219 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/README diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/README:1.1 *** /dev/null Mon Oct 4 15:01:25 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/README Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,2 ---- + Listings 7.5 to 7.15, from "The C++ Workbook" by Wiener and Pinson, + Addison-Wesley, 1990. Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.cpp:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.cpp Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,123 ---- + // Tree.cc + + #include "tree.h" + + void strcpy(char *nam1, char *nam2) {*nam1 = *nam2;} + int strlen(char *nam) {return 0;} + + Tree::Tree(float n) { + nodePtr = new RealNode(n); + } + + Tree::Tree(char* ch) { + nodePtr = new RealNode (0.0,ch); + } + + Tree::Tree(char* op, Tree t) { + nodePtr = new UnaryNode(op,t); + } + + Tree::Tree(Tree left, char* op, Tree right) { + nodePtr = new BinaryNode(op,left,right); + } + + Tree::~Tree(void) { + if (--nodePtr->use == 0) + delete nodePtr; + } + + void Tree::operator =(const Tree& t) { + ++t.nodePtr->use; + if (--nodePtr->use == 0) + delete nodePtr; + nodePtr = t.nodePtr; + } + + Tree::Tree(const Tree& t) { + nodePtr = t.nodePtr; + ++nodePtr->use; + } + + float Tree::value() { + return nodePtr->nodeValue(); + } + + float Tree::operator ()(float x, float y, float z) { + values0 = x, values1 = y, values2 = z; + return this->value(); + } + + // BinaryNode.cc + + #define LARGE 9999999.0 + + BinaryNode::BinaryNode(char*a, Tree b, Tree c) { + left = new Tree(b); right = new Tree(c); + strlen(a), op = new char; + strcpy(op,a); + } + + float BinaryNode::nodeValue() { + float num, den; + + if (*op == '+') + return left->value() + right->value(); + else { + num = left->value(); + den = right->value(); + return LARGE; + } + } + + // UnaryNode.cc + + UnaryNode::UnaryNode(char* a, Tree b) { + opnd = new Tree(b); + strlen(a), op = new char; + strcpy(op,a); + } + + float UnaryNode::nodeValue() { + if (*op == '-') + return -opnd->value(); + else if (*op == '+') + return opnd->value(); + } + + // RealNode.cc + + RealNode::RealNode(float k, char* ch) { + n = k; + if (ch) { + strlen(ch), symbol = new char; + strcpy(symbol,ch); + } + } + + float RealNode::nodeValue() { + if (symbol == 0) + return n; + else if (*symbol == 'x') + return values0; + else if (*symbol == 'y') + return values1; + else + return values2; + } + + // main.cc + + main () { + Tree t1(1), t2("u"), t3(5); + Tree t4(t1,"*",t2); + Tree t5("-",t3); + + t4(12.0, 0, 0); + t5.value(); + + Tree t6(t1,"/",t3); + t6(12.12,0,0); + + Tree t7(t1,"+",t5); + t7.value(); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.h:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.h Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,94 ---- + // Node.h + + class Node { + friend class Tree; + private: + int use; + protected: + Node() {use = 1;} + + virtual float nodeValue() {return 0.0;} + + public: + virtual ~Node(void) {} + }; + + // Tree.h + + class Tree { + private: + Node* nodePtr; + + public: + Tree(float n); + + Tree(char* n); + + Tree(char*, Tree t); + + Tree(Tree left, char*, Tree right); + + Tree(const Tree& t); + + ~Tree(void); + + float value(); + + float operator () (float x, float y, float z); + + void operator =(const Tree& t); + }; + + // RealNode.h + + class RealNode: public Node { + friend class Tree; + private: + float n; + + char* symbol; + + RealNode(float k, char* ch=0); + + ~RealNode(void) {delete symbol; this->Node::~Node();} + + float nodeValue(); + }; + + // UnaryNode.h + + class UnaryNode: public Node { + friend class Tree; + private: + char* op; + + Tree *opnd; + + UnaryNode(char* a, Tree b); + + ~UnaryNode(void) {delete op; delete opnd; this->Node::~Node();} + + float nodeValue(); + }; + + // BinaryNode.h + + class BinaryNode: public Node { + friend class Tree; + private: + char* op; + + Tree* left; + + Tree* right; + + BinaryNode(char* a, Tree b, Tree c); + + ~BinaryNode(void) {delete op; delete left; delete right; this->Node::~Node();} + + float nodeValue(); + }; + + // globals.h + + float values0, values1, values2; From lattner at cs.uiuc.edu Mon Oct 4 15:01:30 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:30 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/README screen1.h screen2.h screen3.h simulate.cpp simulate.h Message-ID: <200410042001.PAA13309@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul: README added (r1.1) screen1.h added (r1.1) screen2.h added (r1.1) screen3.h added (r1.1) simulate.cpp added (r1.1) simulate.h added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+341 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/README diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/README:1.1 *** /dev/null Mon Oct 4 15:01:25 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/README Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,2 ---- + Pages 396-403 with header files from Ch 7. "Using C++" by + Bruce Eckel, McGraw Hill, 1989. Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/screen1.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/screen1.h:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/screen1.h Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,16 ---- + class cursor_controller { + public: + // simple cursor motion: + void up(int rows = 1); + void down(int rows = 1); + void right(int cols = 1); + void left(int cols = 1); // + void move(int row, int col); // absolute positioning + void home() {move(1,1);} + // erasing portions of the screen: + void clear_screen() ; // also send cursor home + void clear_eol(); + void save(); + void restore(); + }; + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/screen2.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/screen2.h:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/screen2.h Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,9 ---- + class cursor_controller2: public cursor_controller { + public: + void normal(); + void high_intensity(); + void blink(); + void reverse(); + void invisible(); + }; + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/screen3.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/screen3.h:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/screen3.h Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,24 ---- + static int object_count; + + class screen_controller : public cursor_controller2 { + int rowmax, colmax; + public: + screen_controller(int rows=25, int cols=80); + void setrows(int rows); + void setcols(int cols); + int maxrow() { return rowmax;} + int maxcol() { return colmax;} + ~screen_controller(); + void upper_left(); + void lower_left(); + void upper_right(); + void lower_right(); + void draw_vertical(int row, int col, int length, char lc); + void draw_horizontal(int row, int col, int length, char lc); + void center(int row, char *text); + void move(int row, int col); + void pause(int seconds=1); + void drawbox(int hor, int ver, int ul, int ur, int ll, int lr); + }; + + extern screen_controller screen; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/simulate.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/simulate.cpp:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/simulate.cpp Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,272 ---- + #include "screen1.h" + + // begin screen1.cpp implementation + + void printf(char *s, int i, int j) {} + + void cursor_controller::up(int rows) { + printf("%dA", rows, 0); + } + + void cursor_controller::down(int rows) { + printf("%dB", rows, 0); + } + + void cursor_controller::right(int cols) { + printf("%dC", cols, 0); + } + + void cursor_controller::left(int cols) { + printf("%dD", cols, 0); + } + + void cursor_controller::move(int row, int col) { + printf("%d;%dH", row, col); + } + + void cursor_controller::clear_screen() { + printf("2J", 0, 0); + } + + void cursor_controller::clear_eol() { + printf("K", 0, 0); + } + + void cursor_controller::save() { + printf("s", 0, 0); + } + + void cursor_controller::restore() { + printf("u", 0, 0); + } + // end screen1.cpp + + #include "screen2.h" + + //begin screen2 implementation + + void cursor_controller2::normal() { + printf("0", 0, 0); + } + + void cursor_controller2::high_intensity() { + printf("1", 0, 0); + } + + void cursor_controller2::blink() { + printf("5", 0, 0); + } + + void cursor_controller2::reverse() { + printf("7", 0, 0); + } + + void cursor_controller2::invisible() { + printf("8", 0, 0); + } + + #include "screen3.h" + + // begin screen3 implementation + + screen_controller screen; + + void error(char *message) {} + int strlen(char *str) {return 0;} + + screen_controller::screen_controller(int rows, int cols) : rowmax(rows), colmax(cols) { + if (object_count) + error("only one instance allowed"); + else + object_count = 1; + printf("turn off wrap", 0, 0); + } + + void screen_controller::setrows(int rows) { + rowmax = rows; + } + + void screen_controller::setcols(int cols) { + colmax = cols; + } + + screen_controller::~screen_controller() { + normal(); + printf("turn on line wrap", 0, 0); + } + + void screen_controller::upper_left() { + move(1, 1); + } + + void screen_controller::lower_left() { + move(rowmax, 1); + } + + void screen_controller::upper_right() { + move(1, colmax); + } + + void screen_controller::lower_right() { + move(rowmax, colmax); + } + + void screen_controller::draw_vertical(int row, int col, int length, char l_char) { + if (row > rowmax || (row+length) > rowmax) + error("draw_vertical: row index out of bounds"); + if (col > colmax) + error("draw_vertical: col index out of bounds"); + for (int rrow = row; rrow <= row+length; rrow++) { + cursor_controller::move(rrow,col); + printf("%c", (int) l_char, 0); + } + } + + void screen_controller::draw_horizontal(int row, int col, int length, char l_char) { + if (col > colmax || (col+length) > colmax) + error("draw_horizontal: row index out of bounds"); + if (row > rowmax) + error("draw_horizontal: col index out of bounds"); + for (int ccol = col; ccol <= col+length; ccol++) { + cursor_controller::move(row,ccol); + printf("%c", (int) l_char, 0); + } + } + + void screen_controller::center(int row, char *text) { + move(row, (colmax-strlen(text))/2); + printf("%c", (int) *text, 0); + } + + + void screen_controller::move(int row, int col) { + if (row > rowmax) + error("move: row index out of bounds"); + if (col > colmax) + error("move: col index out of bounds"); + cursor_controller::move(row,col); + } + + void screen_controller::pause(int seconds) {} + + void screen_controller::drawbox(int hor, int ver, int ul, int ur, int ll, int lr) { + draw_vertical(0, 0, maxrow()-1, ver); + draw_vertical(0, maxcol(), maxrow()-1, ver); + draw_horizontal(0, 0, maxcol()-1, hor); + draw_horizontal(maxrow(), 0, maxcol()-1, hor); + upper_left(); printf("%d", ul, 0); + lower_left(); printf("%d", ll, 0); + upper_right(); printf("%d", ur, 0); + lower_right(); printf("%d", lr, 0); + } + + // end screen3 implementation + + #include "simulate.h" + + simulation_unit *s_grid[xsize][ysize]; + + class init_grid { + public: + init_grid(); + }; + + init_grid grid_initializer; + + init_grid::init_grid() { + for (int i = 0; i < xsize; i++) + for (int j = 0; j < ysize; j++) + s_grid[i][j] = 0; + } + + void simulation_unit::move(int x_steps, int y_steps) { + int x_new = x + x_steps; + int y_new = y + y_steps; + if (x_new < 0 || x_new >= xsize) + error("move: x coord out of bounds"); + if (y_new < 0 || y_new >= ysize) + error("move: y coord out of bounds"); + if (s_grid[x_new][y_new] == 0) { + s_grid[x][y] = 0; + erase(); + s_grid[x=x_new][y=y_new] = this; + display(); + } + } + + // now the test of simulation + class pop_around : public simulation_unit { + public: + void display() { + screen.move(x,y); + printf("@", 0, 0); + } + void erase() { + screen.move(x,y); + printf("", 0, 0); + } + pop_around(int xi, int yi) : simulation_unit(xi,yi) { + display(); + } + ~pop_around() {} + void cycle() { + int x_direction; int y_direction; + if (x == 0) x_direction = 0; + else if (x == xsize-1) x_direction = 1; + else x_direction = 2; + if (y == 0) y_direction = 0; + else if (y == ysize-1) y_direction = 1; + else y_direction = 2; + int x_jump = x_direction ? -1 : 1; + int y_jump = y_direction ? -1 : 1; + move(x_jump, y_jump); + } + }; + + class crawl_around : public simulation_unit { + public: + void display() { + screen.move(x,y); + printf("*", 0, 0); + } + void erase() { + screen.move(x,y); + printf("", 0, 0); + } + crawl_around(int xi, int yi) : simulation_unit(xi,yi) { + display(); + } + ~crawl_around() {} + void cycle() { + int x_step = 0 ? -1 : 1; + if (x + x_step < 0) x_step = -x_step; + if (x + x_step >= xsize) x_step = -x_step; + int y_step = 0 ? -1 : 1; + if (y + y_step < 0) y_step = -y_step; + if (y + y_step >= ysize) y_step = -y_step; + move(x_step, y_step); + } + }; + + main() { + screen.clear_screen(); + int pop_factor = 1; + int crawl_factor = 2; + for (int x = 0; x < xsize; x++) + for (int y = 0; y < ysize; y++) { + if (pop_factor) + if (!s_grid[x][y]) + s_grid[x][y] = new pop_around(x,y); + if (crawl_factor) + if (!s_grid[x][y]) + s_grid[x][y] = new crawl_around(x,y); + } + int xrand = 5; + int yrand = 6; + while (1) { + int x_location = xrand; + int y_location = yrand; + if (s_grid[x_location][y_location]) + s_grid[x_location][y_location]->cycle(); + } + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/simulate.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/simulate.h:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/simulate.h Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,18 ---- + #define xsize 25 + #define ysize 80 + + class simulation_unit { + protected: + int x, y; + public: + virtual void display() {} + virtual void erase() {} + simulation_unit(int x_loc, int y_loc) : x(x_loc), y(y_loc) { + display(); + } + virtual ~simulation_unit() {erase();} + virtual void cycle() {} + void move(int x_steps, int y_steps); + }; + + extern simulation_unit *s_grid[xsize][ysize]; From lattner at cs.uiuc.edu Mon Oct 4 15:01:30 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:01:30 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/bjarne.cpp bjarne.h Message-ID: <200410042001.PAA13305@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes: bjarne.cpp added (r1.1) bjarne.h added (r1.1) --- Log message: Initial checkin of all of the source --- Diffs of the changes: (+244 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/bjarne.cpp diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/bjarne.cpp:1.1 *** /dev/null Mon Oct 4 15:01:25 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/bjarne.cpp Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,224 ---- + /* this program is taken from Section 6.4 + in Bjarne Stroustrup's book "The C++ Programming Language" 2nd Edition. */ + #include + #include "bjarne.h" + + enum color {black='*', white=' '}; + + char screen[XMAX][YMAX]; + + void screen_init() { + for (int y=0; y=a && a<=b) y0 += dy, eps -= two_a; + } + } + + void screen_clear() { screen_init(); } + + void screen_refresh() { + for (int y=YMAX-1; 0<=y; y--) { // top to bottom + for (int x=0; xx+e->x)/2,e->yy?w->y:e->y); + return ret; + } + point *south() const + { point *ret = new point((w->x+e->x)/2,e->yy?e->y:w->y); + return ret; + } + point *east() const {} + point *west() const {} + point *neast() const {} + point *seast() const {} + point *nwest() const {} + point *swest() const {} + + void move (int a, int b) { + w->x += a; w->y += b; e->x += a; e->y += b; } + void draw () { put_line(w,e); } + + line(point *a, point *b) { w = a; e = b; } + line(point *a, int l) { w = new point(a->x+l-1,a->y);e = a; } + }; + + class rectangle : public shape { + public: + point *sw,*ne; + point *north() const + { point *ret = new point((sw->x+ne->x)/2,ne->y); + return ret; + } + point *south() const + { point *ret = new point((sw->x+ne->x)/2,sw->y); + return ret; + } + point *east() const {} + point *west() const {} + point *neast() const {return ne;} + point *seast() const {} + point *nwest() const {} + point *swest() const {return sw;} + + void move (int a, int b) { + sw->x += a; sw->y += b; ne->x += a; ne->y += b; } + void draw (); + + rectangle(point *, point *); + }; + + rectangle::rectangle(point *a, point *b) { + if (a->x <= b->x) { + if (a->y <= b->y) { + sw = a; + ne = b; + } + else { + sw = new point(a->x,b->y); + ne = new point(b->x,a->y); + } + } + else { + if (a->y <= b->y) { + sw = new point(b->x,a->y); + ne = new point(a->x,b->y); + } + else { + sw = b; + ne = a; + } + } + } + + void rectangle::draw() { + point nw(sw->x,ne->y); + point se(ne->x,sw->y); + put_line(&nw,ne); + put_line(ne,&se); + put_line(&se,sw); + put_line(sw,&nw); + } + + shape* shape::list = 0; + + void shape_refresh() { + screen_clear(); + for (shape *p = shape::list; p; p=p->next) p->draw(); + screen_refresh(); + } + + void stack(shape *p, const shape *q) { // put p on top of q + point *n = q->north(); + point *s = p->south(); + p->move(n->x-s->x,n->y-s->y+1); + } + + class myshape : public rectangle { + line *l_eye; + line *r_eye; + line *mouth; + public: + myshape(point *a, point *b) : rectangle(a,b) { + int ll = neast()->x-swest()->x+1; + int hh = neast()->y-swest()->y+1; + point *l_eye_point = new point(swest()->x+2,swest()->y+hh*3/4); + point *r_eye_point = new point(swest()->x+ll-4,swest()->y+hh*3/4); + point *mouth_point = new point(swest()->x+2,swest()->y+hh/4); + l_eye = new line(l_eye_point,2); + r_eye = new line(r_eye_point,2); + mouth = new line(mouth_point,ll-4); + } + + void draw(); + void move(int, int); + }; + + void myshape::draw() { + rectangle::draw(); + int a = (swest()->x+neast()->x)/2; + int b = (swest()->y+neast()->y)/2; + put_point(new point(a,b)); + } + + void myshape::move(int a, int b) { + rectangle::move(a,b); + l_eye->move(a,b); + r_eye->move(a,b); + mouth->move(a,b); + } + + int main() { + screen_init(); + point *point00 = new point(0,0); + point *point1010 = new point(10,10); + point *point015 = new point(0,15); + point *point1510 = new point(15,10); + point *point2718 = new point(27,18); + shape *p1 = new rectangle(point00,point1010); + shape *p2 = new line(point015,17); + shape *p3 = new myshape(point1510,point2718); + shape_refresh(); + p3->move(-10,-10); + stack(p2,p3); + stack(p1,p2); + shape_refresh(); + screen_destroy(); + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/bjarne.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/bjarne.h:1.1 *** /dev/null Mon Oct 4 15:01:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/bjarne.h Mon Oct 4 15:01:15 2004 *************** *** 0 **** --- 1,20 ---- + const int XMAX=40; + const int YMAX=24; + + struct point { + int x,y; + point() {} + point(int a, int b) {x=a; y=b;} + }; + + extern void put_point(int a, int b); + inline void put_point(point *p) { put_point(p->x,p->y); } + + extern void put_line(int, int, int, int); + inline void put_line(point *a, point *b) + { put_line(a->x,a->y,b->x,b->y); } + + extern void screen_init(); + extern void screen_destroy(); + extern void screen_refresh(); + extern void screen_clear(); From lattner at cs.uiuc.edu Mon Oct 4 15:07:53 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:07:53 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/Makefile NP.cpp Message-ID: <200410042007.PAA13468@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP: Makefile added (r1.1) NP.cpp updated: 1.1 -> 1.2 --- Log message: Update this benchmark to actually compile --- Diffs of the changes: (+24 -11) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/Makefile:1.1 *** /dev/null Mon Oct 4 15:07:50 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/Makefile Mon Oct 4 15:07:40 2004 *************** *** 0 **** --- 1,12 ---- + LEVEL = ../../../.. + + PROG = np + #CPPFLAGS = -DVERSION='"1.00"' -DCOMPDATE="\"today\"" -DCFLAGS='""' -DHOSTNAME="\"thishost\"" + LDFLAGS = -lstdc++ + ifdef LARGE_PROBLEM_SIZE + #RUN_OPTIONS = ref.in + else + #RUN_OPTIONS = test.in + endif + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp:1.1 Mon Oct 4 15:01:10 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp Mon Oct 4 15:07:40 2004 @@ -2,34 +2,35 @@ // Written by Hemant Pande, Rutgers University. December 1994. May be // distributed freely, provided this comment is displayed at the top. // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + class True { public: True() {} - virtual True *and (True *arg) + virtual True *and_m (True *arg) { return arg; } -} true; +} tru; class False : public True { public: False() {} - True *and (True *arg); -} false; + True *and_m (True *arg); +} fals; -True *False::and (True *arg) +True *False::and_m (True *arg) { - return &false; + return &fals; } True *v1, *nv1, *v2, *nv2, *v3, *nv3; True *c; main () { - if (0) {v1 = &true; nv1 = &false;} else {v1 = &false; nv1= &true;} - if (0) {v2 = &true; nv2 = &false;} else {v2 = &false; nv2 = &true;} - if (0) {v3 = &true; nv3 = &false;} else {v3 = &false; nv3 = &true;} + if (0) {v1 = &tru; nv1 = &fals;} else {v1 = &fals; nv1= &tru;} + if (0) {v2 = &tru; nv2 = &fals;} else {v2 = &fals; nv2 = &tru;} + if (0) {v3 = &tru; nv3 = &fals;} else {v3 = &fals; nv3 = &tru;} if (0) c = nv2; else if (0) c = v1; else c = v2; - if (0) c = c->and(nv3); else if (0) c = c->and(nv2); else c = c->and(v1); - if (0) c = c->and(v2); else if (0) c = c->and(nv1); else c = c->and(v3); + if (0) c = c->and_m(nv3); else if (0) c = c->and_m(nv2); else c = c->and_m(v1); + if (0) c = c->and_m(v2); else if (0) c = c->and_m(nv1); else c = c->and_m(v3); } From lattner at cs.uiuc.edu Mon Oct 4 15:08:53 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:08:53 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp Message-ID: <200410042008.PAA13555@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP: NP.cpp updated: 1.2 -> 1.3 --- Log message: Give this some output --- Diffs of the changes: (+4 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp:1.2 llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp:1.3 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp:1.2 Mon Oct 4 15:07:40 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/NP.cpp Mon Oct 4 15:08:42 2004 @@ -3,11 +3,14 @@ // distributed freely, provided this comment is displayed at the top. // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +#include + class True { public: True() {} virtual True *and_m (True *arg) { + printf("T\n"); return arg; } } tru; @@ -20,6 +23,7 @@ True *False::and_m (True *arg) { + printf("F\n"); return &fals; } From lattner at cs.uiuc.edu Mon Oct 4 15:10:34 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:10:34 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chess.cpp Message-ID: <200410042010.PAA13679@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess: chess.cpp updated: 1.1 -> 1.2 --- Log message: Allow this to compile --- Diffs of the changes: (+4 -4) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chess.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chess.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chess.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chess.cpp:1.1 Mon Oct 4 15:01:12 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chess.cpp Mon Oct 4 15:10:24 2004 @@ -37,12 +37,12 @@ config [1][i] = new Pawn(CH_BLACK); config [6][i] = new Pawn(CH_WHITE); } - for (i=0;i<8;i++) + for (int i=0;i<8;i++) for (int j=2;j<6;j++) config [j][i] = 0; } -Board :: Move (Pos *f, Pos *t) +int Board :: Move (Pos *f, Pos *t) { config [t->x][t->y] = config [f->x][f->y]; config [f->x][f->y] = 0; @@ -74,7 +74,7 @@ PaintBoard (); } -Player :: Move (Pos *f, Pos *t) +int Player :: Move (Pos *f, Pos *t) { board->Move (f, t); board->Dump (); @@ -186,7 +186,7 @@ char gameNotOver = 1; char firstMove = 0; -main () +int main () { // struct stat Stat; // FILE *fp; From gaeke at cs.uiuc.edu Mon Oct 4 15:15:11 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Mon, 4 Oct 2004 15:15:11 -0500 (CDT) Subject: [llvm-commits] CVS: reopt/lib/WholeReoptimizer/ Message-ID: <200410042015.PAA28591@seraph.cs.uiuc.edu> Changes in directory reopt/lib/WholeReoptimizer: --- Log message: Directory /home/vadve/shared/InternalCVS/reopt/lib/WholeReoptimizer added to the repository --- Diffs of the changes: (+0 -0) From gaeke at cs.uiuc.edu Mon Oct 4 15:15:32 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Mon, 4 Oct 2004 15:15:32 -0500 (CDT) Subject: [llvm-commits] CVS: reopt/lib/WholeReoptimizer/Makefile Message-ID: <200410042015.PAA28623@seraph.cs.uiuc.edu> Changes in directory reopt/lib/WholeReoptimizer: Makefile added (r1.1) --- Log message: Add new makefile used to build the whole reoptimizer into a single archive. --- Diffs of the changes: (+55 -0) Index: reopt/lib/WholeReoptimizer/Makefile diff -c /dev/null reopt/lib/WholeReoptimizer/Makefile:1.1 *** /dev/null Mon Oct 4 15:15:31 2004 --- reopt/lib/WholeReoptimizer/Makefile Mon Oct 4 15:15:20 2004 *************** *** 0 **** --- 1,55 ---- + LEVEL = ../.. + + include $(LEVEL)/Makefile.common + + REOPTLIBDIR = $(BUILD_OBJ_ROOT)/lib/$(CONFIGURATION) + + REOPTIMIZER_OBJS = $(REOPTLIBDIR)/firstTrigger.o \ + $(REOPTLIBDIR)/tracecache.o $(REOPTLIBDIR)/mapinfo.o \ + $(REOPTLIBDIR)/scratchmemory.o $(REOPTLIBDIR)/tracetofunction.o \ + $(REOPTLIBDIR)/tracejit.o $(REOPTLIBDIR)/traceio.o + + # Object files that contain common LLVM code the Reoptimizer depends on + REOPTIMIZER_LLVMOBJS = $(LLVMLIBCURRENTSOURCE)/vmcore.o \ + $(LLVMLIBCURRENTSOURCE)/bcreader.o $(LLVMLIBCURRENTSOURCE)/bcwriter.o \ + $(LLVMLIBCURRENTSOURCE)/sparcv9.o \ + $(LLVMLIBCURRENTSOURCE)/sparcv9livevar.o \ + $(LLVMLIBCURRENTSOURCE)/sched.o $(LLVMLIBCURRENTSOURCE)/codegen.o \ + $(LLVMLIBCURRENTSOURCE)/executionengine.o \ + $(LLVMLIBCURRENTSOURCE)/lli-jit.o \ + $(LLVMLIBCURRENTSOURCE)/lli-interpreter.o + + # Library archive files that contain common LLVM code the Reoptimizer depends on + REOPTIMIZER_LLVMLIBS = $(LLVMLIBCURRENTSOURCE)/libsparcv9regalloc.a \ + $(LLVMLIBCURRENTSOURCE)/libtarget.a \ + $(LLVMLIBCURRENTSOURCE)/libscalaropts.a \ + $(LLVMLIBCURRENTSOURCE)/libtransformutils.a \ + $(LLVMLIBCURRENTSOURCE)/libanalysis.a \ + $(LLVMLIBCURRENTSOURCE)/libsupport.a \ + $(LLVMLIBCURRENTSOURCE)/libLLVMsystem.a + + WHOLE_REOPTIMIZER_LIB = $(BUILD_OBJ_ROOT)/lib/$(CONFIGURATION)/libwholereoptimizer.a + + all:: $(WHOLE_REOPTIMIZER_LIB) + + $(WHOLE_REOPTIMIZER_LIB): $(REOPTIMIZER_OBJS) $(REOPTIMIZER_LLVMOBJS) $(REOPTIMIZER_LLVMLIBS) + $(VERB) rm -f $@ + @echo "Building $(WHOLE_REOPTIMIZER_LIB)" + @echo "Adding reoptimizer .o files to libwholereoptimizer.a" + $(VERB) ar rc $@ $(REOPTIMIZER_OBJS) $(REOPTIMIZER_LLVMOBJS) + $(VERB) @for lib in $(REOPTIMIZER_LLVMLIBS); \ + do \ + echo "Adding files from $${lib} to libwholereoptimizer.a"; \ + d=`basename $${lib}`x; \ + mkdir $${d}; \ + cd $${d}; \ + ar x $$lib; \ + ar q $@ *; \ + cd ..; \ + rm -rf $${d}; \ + done + @echo "==== Done building libwholereoptimizer.a ====" + + clean:: + $(VERB) rm -f $(WHOLE_REOPTIMIZER_LIB) + From gaeke at cs.uiuc.edu Mon Oct 4 15:15:39 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Mon, 4 Oct 2004 15:15:39 -0500 (CDT) Subject: [llvm-commits] CVS: reopt/test/run-tests Message-ID: <200410042015.PAA28647@seraph.cs.uiuc.edu> Changes in directory reopt/test: run-tests updated: 1.21 -> 1.22 --- Log message: When testing spec programs, use 'gmake -k', so that the tests don't stop at some random failure point. --- Diffs of the changes: (+1 -1) Index: reopt/test/run-tests diff -u reopt/test/run-tests:1.21 reopt/test/run-tests:1.22 --- reopt/test/run-tests:1.21 Thu Sep 23 14:48:38 2004 +++ reopt/test/run-tests Mon Oct 4 15:15:29 2004 @@ -147,7 +147,7 @@ # note: SPEC Sandbox.sh does NOT play nice with our debug output! LLVM_REOPT='--enable-trace-opt' export LLVM_REOPT - exec gmake SUBDIR=$SUBDIR SPECTEST=1 RUNTIMELIMIT=900 $MKOPTS + exec gmake -k SUBDIR=$SUBDIR SPECTEST=1 RUNTIMELIMIT=900 $MKOPTS else exec gmake SUBDIR=$SUBDIR RUNTIMELIMIT=900 $MKOPTS fi From gaeke at cs.uiuc.edu Mon Oct 4 15:15:38 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Mon, 4 Oct 2004 15:15:38 -0500 (CDT) Subject: [llvm-commits] CVS: reopt/test/TEST.reopt.Makefile Message-ID: <200410042015.PAA28641@seraph.cs.uiuc.edu> Changes in directory reopt/test: TEST.reopt.Makefile updated: 1.25 -> 1.26 --- Log message: Use the new "whole reoptimizer" library. --- Diffs of the changes: (+3 -39) Index: reopt/test/TEST.reopt.Makefile diff -u reopt/test/TEST.reopt.Makefile:1.25 reopt/test/TEST.reopt.Makefile:1.26 --- reopt/test/TEST.reopt.Makefile:1.25 Fri Oct 1 13:51:34 2004 +++ reopt/test/TEST.reopt.Makefile Mon Oct 4 15:15:28 2004 @@ -28,47 +28,11 @@ REOPTLLC = $(PROJECT_DIR)/tools/$(CONFIGURATION)/reopt-llc # Libraries that contain the Reoptimizer itself -#REOPTIMIZER_OBJS = $(PROJECT_DIR)/lib/Debug/firstTrigger.o - -REOPTIMIZER_OBJS = $(REOPTLIBDIR)/firstTrigger.o \ - $(REOPTLIBDIR)/tracecache.o $(REOPTLIBDIR)/mapinfo.o \ - $(REOPTLIBDIR)/scratchmemory.o $(REOPTLIBDIR)/tracetofunction.o \ - $(REOPTLIBDIR)/tracejit.o $(REOPTLIBDIR)/traceio.o - -# Object files that contain common LLVM code the Reoptimizer depends on -REOPTIMIZER_LLVMOBJS = $(LLVMLIBCURRENTSOURCE)/vmcore.o \ - $(LLVMLIBCURRENTSOURCE)/bcreader.o $(LLVMLIBCURRENTSOURCE)/bcwriter.o \ - $(LLVMLIBCURRENTSOURCE)/sparcv9.o \ - $(LLVMLIBCURRENTSOURCE)/sparcv9livevar.o $(LLVMLIBCURRENTSOURCE)/sched.o \ - $(LLVMLIBCURRENTSOURCE)/codegen.o $(LLVMLIBCURRENTSOURCE)/executionengine.o \ - $(LLVMLIBCURRENTSOURCE)/lli-jit.o $(LLVMLIBCURRENTSOURCE)/lli-interpreter.o - -# Library archive files that contain common LLVM code the Reoptimizer depends on -REOPTIMIZER_LLVMLIBS = $(LLVMLIBCURRENTSOURCE)/libsparcv9regalloc.a \ - $(LLVMLIBCURRENTSOURCE)/libtarget.a \ - $(LLVMLIBCURRENTSOURCE)/libscalaropts.a \ - $(LLVMLIBCURRENTSOURCE)/libtransformutils.a \ - $(LLVMLIBCURRENTSOURCE)/libanalysis.a \ - $(LLVMLIBCURRENTSOURCE)/libsupport.a \ - $(LLVMLIBCURRENTSOURCE)/libLLVMsystem.a +REOPTIMIZER_LIB = $(REOPTLIBDIR)/libwholereoptimizer.a # Solaris libraries that the Reoptimizer depends on REOPTIMIZER_SOLARISLIBS = -lcpc -lm -lrt -lmalloc -ldl -MYLD = $(shell $(CXX) --print-prog-name=ld) - -WHOLE_REOPTIMIZER = $(REOPTLIBDIR)/wholereoptimizer.o -$(WHOLE_REOPTIMIZER): $(REOPTIMIZER_OBJS) $(REOPTIMIZER_LLVMOBJS) - $(MYLD) -r -o $@ $+ - -# Libraries that should be checked for freshness when doing -# Reoptimizer tests (http://www.goodegg.com/eggdating.html) -REOPTIMIZER_LIBDEPS = $(WHOLE_REOPTIMIZER) $(REOPTIMIZER_LLVMLIBS) - -# Things that need to be added to the link line when linking a -# program with the Reoptimizer -REOPTIMIZER_LDADD = $(WHOLE_REOPTIMIZER) $(REOPTIMIZER_LLVMLIBS) $(REOPTIMIZER_SOLARISLIBS) - .PRECIOUS: Output/%.out-reopt-llc $(PROGRAMS_TO_TEST:%=test.$(TEST).%): \ @@ -94,8 +58,8 @@ # 2. Link the instrumented binary with the necessary parts of the # compiler. $(PROGRAMS_TO_TEST:%=Output/%.reopt-llc): \ -Output/%.reopt-llc: Output/%.reopt-llc.s $(REOPTIMIZER_LIBDEPS) - $(CXX) $(CFLAGS) $< -o $@ $(REOPTIMIZER_LDADD) +Output/%.reopt-llc: Output/%.reopt-llc.s $(REOPTIMIZER_LIB) + $(CXX) $(CFLAGS) $< -o $@ $(REOPTIMIZER_LIB) $(REOPTIMIZER_SOLARISLIBS) # 3. Run the reoptimized version. ifdef SPECTEST From gaeke at cs.uiuc.edu Mon Oct 4 15:15:37 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Mon, 4 Oct 2004 15:15:37 -0500 (CDT) Subject: [llvm-commits] CVS: reopt/lib/Makefile Message-ID: <200410042015.PAA28629@seraph.cs.uiuc.edu> Changes in directory reopt/lib: Makefile updated: 1.23 -> 1.24 --- Log message: Add directory with makefile for "whole reoptimizer" library to the build. --- Diffs of the changes: (+1 -1) Index: reopt/lib/Makefile diff -u reopt/lib/Makefile:1.23 reopt/lib/Makefile:1.24 --- reopt/lib/Makefile:1.23 Wed Jun 30 01:33:09 2004 +++ reopt/lib/Makefile Mon Oct 4 15:15:26 2004 @@ -1,5 +1,5 @@ LEVEL = .. -DIRS := BinInterface Mapping TraceCache Trigger LightWtProfiling Inst Optimizations TraceToFunction TraceJIT TraceIO +DIRS := BinInterface Mapping TraceCache Trigger LightWtProfiling Inst Optimizations TraceToFunction TraceJIT TraceIO WholeReoptimizer include $(LEVEL)/Makefile.config From gaeke at cs.uiuc.edu Mon Oct 4 15:15:37 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Mon, 4 Oct 2004 15:15:37 -0500 (CDT) Subject: [llvm-commits] CVS: reopt/lib/LightWtProfiling/SecondTrigger.cpp Message-ID: <200410042015.PAA28635@seraph.cs.uiuc.edu> Changes in directory reopt/lib/LightWtProfiling: SecondTrigger.cpp updated: 1.35 -> 1.36 --- Log message: Make sure we always express paths as type uint64_t. Add new function constructFullVBB that collapses multiple paths together into a hyperblock. Use it to make a trace consisting of *all* the paths for which we have counter data, instead of just the first path. This is a hack to reduce the number of trace entrances/exits. --- Diffs of the changes: (+33 -3) Index: reopt/lib/LightWtProfiling/SecondTrigger.cpp diff -u reopt/lib/LightWtProfiling/SecondTrigger.cpp:1.35 reopt/lib/LightWtProfiling/SecondTrigger.cpp:1.36 --- reopt/lib/LightWtProfiling/SecondTrigger.cpp:1.35 Thu Sep 23 14:48:34 2004 +++ reopt/lib/LightWtProfiling/SecondTrigger.cpp Mon Oct 4 15:15:27 2004 @@ -18,6 +18,7 @@ #include "ReoptimizerInternal.h" #include "RegSaveRestore.h" +#include "llvm/ADT/SetVector.h" #include "llvm/Support/Debug.h" #include "llvm/Function.h" #include "llvm/Instructions.h" @@ -410,7 +411,7 @@ /// BRANCH which is on the trace. As a side effect, modifies PATH /// so that it starts at the returned basic block. /// -BasicBlock *getSuccessorByPath (BranchInst &branch, unsigned &path) +BasicBlock *getSuccessorByPath (BranchInst &branch, uint64_t &path) { BasicBlock *bb; @@ -433,7 +434,7 @@ /// address is START, construct in VBB a vector of LLVM BasicBlocks /// that represents the trace. /// -void constructVBB (unsigned int path, uint64_t start, +void constructVBB (uint64_t path, uint64_t start, std::vector &vBB) { BasicBlock *bb; BasicBlock *startBB = 0; @@ -464,6 +465,35 @@ } while (bb != vBB[0]); } +/// Given a vector of paths PATHS starting in the basic block whose machine +/// address is START, construct in VBB a vector of LLVM BasicBlocks +/// that represents the trace. +/// +void constructFullVBB (std::vector &paths, uint64_t start, + std::vector &vBB) { + BasicBlock *bb; + BasicBlock *startBB = 0; + SetVector svBB; + // Get the first basic block by querying the mapping information. + bool foundBB = getReverseBBMap (start, M, startBB); + assert (foundBB && "Couldn't find starting BasicBlock for trace start addr"); + bb = startBB; + for (unsigned i = 0; i < paths.size (); ++i) { + uint64_t path = paths[i]; + do { + // Add basic block to trace, eliminating duplicates. + svBB.insert (bb); + // Try to find the next basic block. + // Silently fail if we have a basic block in the trace that + // ends in something other than a branch. + BranchInst *BI = dyn_cast (bb->getTerminator ()); + if (!BI) return; + bb = getSuccessorByPath (*BI, path); + } while (bb != startBB); + } + vBB.assign (svBB.begin (), svBB.end ()); +} + void addCall(std::vector &traces, std::map &callMap, int &index, uint64_t addressOfCall) @@ -525,7 +555,7 @@ if (enable_trace_optimizer) { //use path 0 to form vBB std::vector vBB; - constructVBB (paths[0], start, vBB); + constructFullVBB (paths, start, vBB); if (vBB.empty()) return; if (!optimizeTrace (vBB, firstLevelTraceStartAddr)) { // give up. From gaeke at cs.uiuc.edu Mon Oct 4 15:23:19 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Mon, 4 Oct 2004 15:23:19 -0500 Subject: [llvm-commits] CVS: reopt/lib/LightWtProfiling/Initialization.cpp Message-ID: <200410042023.PAA14417@zion.cs.uiuc.edu> Changes in directory reopt/lib/LightWtProfiling: Initialization.cpp updated: 1.19 -> 1.20 --- Log message: Rearrange cl::opts. Add more descriptions of options. We only need one option for the timer threshold. --- Diffs of the changes: (+28 -17) Index: reopt/lib/LightWtProfiling/Initialization.cpp diff -u reopt/lib/LightWtProfiling/Initialization.cpp:1.19 reopt/lib/LightWtProfiling/Initialization.cpp:1.20 --- reopt/lib/LightWtProfiling/Initialization.cpp:1.19 Thu Sep 2 11:55:43 2004 +++ reopt/lib/LightWtProfiling/Initialization.cpp Mon Oct 4 15:23:09 2004 @@ -21,6 +21,8 @@ #include "reopt/TraceCache.h" #include "reopt/VirtualMem.h" #include +#include +#include #include namespace llvm { @@ -49,27 +51,32 @@ // FIXME: What are the units of these next two? cl::opt -InstTraceCacheSize("inst-trace-cache-size", cl::init(30000), - cl::desc("Trace cache size for SLI-instrumented code")); + InstTraceCacheSize("inst-trace-cache-size", cl::init(30000), + cl::desc("Trace cache size for SLI-instrumented code")); cl::opt -OptTraceCacheSize("opt-trace-cache-size", cl::init(30000), - cl::desc("Trace cache size for optimized code")); + OptTraceCacheSize("opt-trace-cache-size", cl::init(30000), + cl::desc("Trace cache size for optimized code")); cl::opt -FLIThreshold("fli-threshold", cl::location(reopt_threshold), cl::init(30)); + FLIThreshold("fli-threshold", cl::location(reopt_threshold), cl::init(30), + cl::desc("Number of times FLI must trigger before attempting SLI")); cl::opt -SLIThreshold("sli-threshold", cl::location(THRESHOLD_LEVEL_2), cl::init(50)); -cl::opt -TimerIntS("timer-int-s", cl::location(timer_interval_sec), cl::init(3)); -cl::opt -TimerIntNS("timer-int-ns", cl::location(timer_interval_nsec), cl::init(0)); + SLIThreshold("sli-threshold", cl::location(THRESHOLD_LEVEL_2), cl::init(50), + cl::desc("Number of iterations of SLI before path counters are sampled")); cl::opt -CountTraceCycles("count-trace-cycles", cl::location(count_trace_cycles)); + CountTraceCycles("count-trace-cycles", cl::location(count_trace_cycles), + cl::desc("Insert entry/exit instrumentation calls to libcpc to count cycles, when using trace layout engine")); cl::opt -EnableTraceOpt("enable-trace-opt", cl::location(enable_trace_optimizer)); -cl::opt -EnablePhaseDetect("enable-phase-detect", cl::location(enable_phase_detect)); + EnableTraceOpt("enable-trace-opt", cl::location(enable_trace_optimizer), + cl::desc("Use the new trace optimizer instead of the old trace layout engine")); cl::opt -SkipTraceOpt("skip-trace", cl::init(-1)); + SkipTraceOpt("skip-trace", cl::init(-1), + cl::desc("Don't optimize the Nth trace, when using trace optimizer")); +cl::opt + EnablePhaseDetect("enable-phase-detect", cl::location(enable_phase_detect), + cl::desc("Use a timer interrupt to remove traces periodically from the trace cache")); +cl::opt + TimerIntS("timer-int-s", cl::init(3.0), + cl::desc("Interval (in seconds) between phase detection sweeps")); /// reoptimizerInitialize - Initialization method for the /// reoptimizer. A call to this function from main() is inserted by @@ -88,8 +95,12 @@ LEVEL_TWO_EXITS = THRESHOLD_LEVEL_2/3; // Set up the phase-change detection stuff (normally disabled). - if (enable_phase_detect) - initialize_timer(); + if (enable_phase_detect) { + double d = TimerIntS; + timer_interval_sec = (int32_t) trunc (d); + timer_interval_nsec = (int32_t) ((d - trunc (d)) * 1.0e9); + initialize_timer (); + } if (SkipTraceOpt != -1) { skipTrace.insert((int)SkipTraceOpt); } From lattner at cs.uiuc.edu Mon Oct 4 15:53:01 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 15:53:01 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess/chess.cpp chessgame.h piece.h Message-ID: <200410042053.PAA13943@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/chess: chess.cpp (r1.2) removed chessgame.h (r1.1) removed piece.h (r1.1) removed --- Log message: This program isn't even close to working, I give up --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 16:08:48 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 16:08:48 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/broken_light.h check_functions.h light.h main.cpp roadlet.cpp roadlet.h vehicle.h Message-ID: <200410042108.QAA14292@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/city: broken_light.h updated: 1.1 -> 1.2 check_functions.h updated: 1.1 -> 1.2 light.h updated: 1.1 -> 1.2 main.cpp updated: 1.1 -> 1.2 roadlet.cpp updated: 1.1 -> 1.2 roadlet.h updated: 1.1 -> 1.2 vehicle.h updated: 1.1 -> 1.2 --- Log message: A few stabs at making this compile --- Diffs of the changes: (+18 -21) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/broken_light.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/broken_light.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/broken_light.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/broken_light.h:1.1 Mon Oct 4 15:01:12 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/broken_light.h Mon Oct 4 16:08:35 2004 @@ -5,7 +5,7 @@ #include "light.h" #include "stream.h" -extern "C" random(); +#include #define BROKEN_LIGHT_ID 1 @@ -17,7 +17,7 @@ broken_light(int t1, int t2, int t3, int t4) : light (t1,t2,t3,t4){}; }; -inline virtual int broken_light::next_state() +inline int broken_light::next_state() { cout << "next state called\n"; if ((random() % 4) == 1) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.h Mon Oct 4 16:08:35 2004 @@ -18,4 +18,4 @@ extern roadlet *green_light(intersection_roadlet*, vehicle*, direction); extern roadlet *green_OR_plan_rightONred(intersection_roadlet*, vehicle*, direction); -#endif _check_function +#endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/light.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/light.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/light.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/light.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/light.h Mon Oct 4 16:08:35 2004 @@ -2,7 +2,8 @@ #ifndef _light_h #define _light_h -#include "ostream.h" +#include +using namespace std; #define LIGHT_ID 0 @@ -23,12 +24,12 @@ light(int t1, int t2, int t3, int t4) {init(t1,t2,t3,t4);}; void tick(); - redNS() {return ((current_state == 0) || (current_state == 1));}; - yellowNS() {return (current_state == 3);}; - greenNS() {return (current_state == 2);}; - redEW() {return ((current_state == 2) || (current_state == 3));}; - yellowEW() {return (current_state == 1);}; - greenEW() {return (current_state == 0);}; + int redNS() {return ((current_state == 0) || (current_state == 1));}; + int yellowNS() {return (current_state == 3);}; + int greenNS() {return (current_state == 2);}; + int redEW() {return ((current_state == 2) || (current_state == 3));}; + int yellowEW() {return (current_state == 1);}; + int greenEW() {return (current_state == 0);}; friend ostream& operator<< (ostream &, light); }; typedef light light_type; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp Mon Oct 4 16:08:35 2004 @@ -7,11 +7,7 @@ #include "roadlet.h" #include "check_functions.h" #include "intersection.h" -extern "C" -{ - void *malloc(); - void srandom(int); -} +#include // connect r1->d1 to r2->d2 Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.cpp:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.cpp Mon Oct 4 16:08:35 2004 @@ -1,6 +1,6 @@ // roadlet.cc -#include +#include #include "roadlet.h" void roadlet::init(char *n) @@ -11,7 +11,7 @@ } -ostream& operator<<(ostream& o, roadlet r) +std::ostream& operator<<(std::ostream& o, roadlet r) { o << "roadlet " << r.name; return (o); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h Mon Oct 4 16:08:35 2004 @@ -19,12 +19,12 @@ protected: char *name; - vehicle *occupant = NULL; - roadlet *neighbors[8] = { NULL }; + vehicle *occupant; + roadlet *neighbors[8]; move_function the_moves[8]; public: - roadlet() { init("unnamed");}; + roadlet() : occupant(NULL) { neighbors[0] = neighbors[1] = neighbors[2] = neighbors[3] = neighbors[4] = neighbors[5] = neighbors[6] = neighbors[7] = 0; init("unnamed");}; roadlet(char *n) { init(n);}; int occupied() { return(occupiedby() != NULL);}; vehicle *occupiedby() {return(occupant);}; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.h Mon Oct 4 16:08:35 2004 @@ -8,7 +8,7 @@ class vehicle { private: - const int DEFAULT_SPEED = 100; + enum { DEFAULT_SPEED = 100 }; roadlet *location; char *name; int speed; From lattner at cs.uiuc.edu Mon Oct 4 16:09:34 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 16:09:34 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/stream.h Message-ID: <200410042109.QAA14322@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/city: stream.h added (r1.1) --- Log message: Oh yeah, need this too --- Diffs of the changes: (+3 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/stream.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/stream.h:1.1 *** /dev/null Mon Oct 4 16:09:33 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/stream.h Mon Oct 4 16:09:23 2004 *************** *** 0 **** --- 1,3 ---- + + #include + using namespace std; From gaeke at cs.uiuc.edu Mon Oct 4 16:18:34 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Mon, 4 Oct 2004 16:18:34 -0500 (CDT) Subject: [llvm-commits] CVS: reopt/lib/LightWtProfiling/Initialization.cpp Message-ID: <200410042118.QAA29432@seraph.cs.uiuc.edu> Changes in directory reopt/lib/LightWtProfiling: Initialization.cpp updated: 1.20 -> 1.21 --- Log message: Shorten description of -count-trace-cycles. I didn't realize trunc() was C99, and not available via Solaris's . So, out it goes. --- Diffs of the changes: (+3 -3) Index: reopt/lib/LightWtProfiling/Initialization.cpp diff -u reopt/lib/LightWtProfiling/Initialization.cpp:1.20 reopt/lib/LightWtProfiling/Initialization.cpp:1.21 --- reopt/lib/LightWtProfiling/Initialization.cpp:1.20 Mon Oct 4 15:23:09 2004 +++ reopt/lib/LightWtProfiling/Initialization.cpp Mon Oct 4 16:18:24 2004 @@ -64,7 +64,7 @@ cl::desc("Number of iterations of SLI before path counters are sampled")); cl::opt CountTraceCycles("count-trace-cycles", cl::location(count_trace_cycles), - cl::desc("Insert entry/exit instrumentation calls to libcpc to count cycles, when using trace layout engine")); + cl::desc("Count cycles in optimized trace, when using trace layout engine")); cl::opt EnableTraceOpt("enable-trace-opt", cl::location(enable_trace_optimizer), cl::desc("Use the new trace optimizer instead of the old trace layout engine")); @@ -97,8 +97,8 @@ // Set up the phase-change detection stuff (normally disabled). if (enable_phase_detect) { double d = TimerIntS; - timer_interval_sec = (int32_t) trunc (d); - timer_interval_nsec = (int32_t) ((d - trunc (d)) * 1.0e9); + timer_interval_sec = (int32_t) d; + timer_interval_nsec = (int32_t) ((d - ((int32_t)d)) * 1.0e9); initialize_timer (); } From gaeke at cs.uiuc.edu Mon Oct 4 16:18:35 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Mon, 4 Oct 2004 16:18:35 -0500 (CDT) Subject: [llvm-commits] CVS: reopt/lib/LightWtProfiling/RuntimeOptimizations.cpp Message-ID: <200410042118.QAA29439@seraph.cs.uiuc.edu> Changes in directory reopt/lib/LightWtProfiling: RuntimeOptimizations.cpp updated: 1.51 -> 1.52 --- Log message: Fix doxygen comment for isFirstTriggerCall(). Remove -allow-calls option -- currently, turning it on would be completely broken. --- Diffs of the changes: (+1 -3) Index: reopt/lib/LightWtProfiling/RuntimeOptimizations.cpp diff -u reopt/lib/LightWtProfiling/RuntimeOptimizations.cpp:1.51 reopt/lib/LightWtProfiling/RuntimeOptimizations.cpp:1.52 --- reopt/lib/LightWtProfiling/RuntimeOptimizations.cpp:1.51 Thu Sep 23 14:48:33 2004 +++ reopt/lib/LightWtProfiling/RuntimeOptimizations.cpp Mon Oct 4 16:18:25 2004 @@ -42,10 +42,8 @@ << std::dec); } -cl::opt AllowCalls("allow-calls", cl::init(false)); /// isFirstTriggerCall - Returns true iff I is a call instruction which -//appears -/// to call into the first-level trigger function. +/// appears to call into the first-level trigger function. /// static bool isFirstTriggerCall (const Instruction &I) { if (const CallInst *CI = dyn_cast (&I)) { From gaeke at cs.uiuc.edu Mon Oct 4 16:18:36 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Mon, 4 Oct 2004 16:18:36 -0500 (CDT) Subject: [llvm-commits] CVS: reopt/lib/TraceJIT/TraceJITOpts.cpp Message-ID: <200410042118.QAA29446@seraph.cs.uiuc.edu> Changes in directory reopt/lib/TraceJIT: TraceJITOpts.cpp updated: 1.4 -> 1.5 --- Log message: Give -run-opt-passes a description. --- Diffs of the changes: (+2 -1) Index: reopt/lib/TraceJIT/TraceJITOpts.cpp diff -u reopt/lib/TraceJIT/TraceJITOpts.cpp:1.4 reopt/lib/TraceJIT/TraceJITOpts.cpp:1.5 --- reopt/lib/TraceJIT/TraceJITOpts.cpp:1.4 Thu Sep 2 11:55:45 2004 +++ reopt/lib/TraceJIT/TraceJITOpts.cpp Mon Oct 4 16:18:26 2004 @@ -18,7 +18,8 @@ using namespace llvm; namespace { - cl::opt RunOptimizationPasses ("run-opt-passes", cl::init(false)); + cl::opt RunOptimizationPasses ("run-opt-passes", cl::init(false), + cl::desc("Run optimization passes before unpacking TraceFunction")); }; void TraceJIT::addOptimizationPasses (FunctionPassManager &PM) { From lattner at cs.uiuc.edu Mon Oct 4 16:19:41 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 16:19:41 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.cpp intersection.cpp intersection.h main.cpp roadlet.h vehicle.cpp vehicle.h Message-ID: <200410042119.QAA14681@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/city: check_functions.cpp updated: 1.1 -> 1.2 intersection.cpp updated: 1.1 -> 1.2 intersection.h updated: 1.1 -> 1.2 main.cpp updated: 1.2 -> 1.3 roadlet.h updated: 1.2 -> 1.3 vehicle.cpp updated: 1.1 -> 1.2 vehicle.h updated: 1.2 -> 1.3 --- Log message: Stab stab stab, we now compile this --- Diffs of the changes: (+37 -35) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.cpp:1.1 Mon Oct 4 15:01:12 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/check_functions.cpp Mon Oct 4 16:19:29 2004 @@ -27,7 +27,7 @@ //check both left and right. This makes sense for roads of two or fewer lanes. roadlet * lane_switch_ok(roadlet *r, vehicle *v, direction d) { - direction dir = v->direction(); + direction dir = v->get_direction(); //cout << "dir = " << dir << "\n"; cout << "lane switch for " << *v << " at " << *r <<'\n'; @@ -55,7 +55,7 @@ //f from notes roadlet * strait (roadlet *r, vehicle *v, direction d) { - if (!r->occupied() && (v->direction() == d)) + if (!r->occupied() && (v->get_direction() == d)) return(r); else return(NULL); @@ -68,7 +68,7 @@ roadlet * strait_or_left (roadlet *r, vehicle *v, direction d) { if (!r->occupied() && - ((v->direction() == d) || (v->direction().left() == d))) + ((v->get_direction() == d) || (v->get_direction().left() == d))) return(r); else return(NULL); @@ -79,7 +79,7 @@ roadlet * strait_or_right (roadlet *r, vehicle *v, direction d) { if (!r->occupied() && - ((v->direction() == d) || (v->direction().right() == d))) + ((v->get_direction() == d) || (v->get_direction().right() == d))) return(r); else return(NULL); @@ -89,14 +89,14 @@ { if ((d == N) || (d == S)) { - if (!r->occupied() && (r->light()->greenNS())) + if (!r->occupied() && (r->get_light()->greenNS())) return(r); else return(NULL); } else { - if (!r->occupied() && (r->light()->greenEW())) + if (!r->occupied() && (r->get_light()->greenEW())) return(r); else return(NULL); @@ -115,13 +115,13 @@ if ((d == N) || (d == S)) { - right_on_red = (r->light()->redNS()) ; // && no on coming traffic - green_light = r->light()->greenNS(); + right_on_red = (r->get_light()->redNS()) ; // && no on coming traffic + green_light = r->get_light()->greenNS(); } else { - right_on_red = (r->light()->redEW()) ; // && no on coming traffic - green_light = r->light()->greenEW(); + right_on_red = (r->get_light()->redEW()) ; // && no on coming traffic + green_light = r->get_light()->greenEW(); } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.cpp:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.cpp Mon Oct 4 16:19:30 2004 @@ -1,56 +1,56 @@ // build_intersection.cc #include "intersection.h" -extern "C" char *malloc(); +#include void intersection_4x4::connectNin (roadlet *leftlane, roadlet *rightlane) { - connect(leftlane, S, roadlets[0][1], N, green_light); - connect(rightlane, S, roadlets[0][0], N, green_OR_plan_rightONred); + connect(leftlane, S, roadlets[0][1], N, (filter_fn)green_light); + connect(rightlane, S, roadlets[0][0], N, (filter_fn)green_OR_plan_rightONred); } void intersection_4x4::connectEin (roadlet *leftlane, roadlet *rightlane) { - connect(leftlane, W, roadlets[1][3], E, green_light); - connect(rightlane, W, roadlets[0][3], E, green_OR_plan_rightONred); + connect(leftlane, W, roadlets[1][3], E, (filter_fn)green_light); + connect(rightlane, W, roadlets[0][3], E, (filter_fn)green_OR_plan_rightONred); } void intersection_4x4::connectSin (roadlet *leftlane, roadlet *rightlane) { - connect(leftlane, N, roadlets[3][2], S, green_light); - connect(rightlane, N, roadlets[3][3], S, green_OR_plan_rightONred); + connect(leftlane, N, roadlets[3][2], S, (filter_fn)green_light); + connect(rightlane, N, roadlets[3][3], S, (filter_fn)green_OR_plan_rightONred); } void intersection_4x4::connectWin (roadlet *leftlane, roadlet *rightlane) { - connect(leftlane, E, roadlets[2][0], W, green_light); - connect(rightlane, E, roadlets[3][0], W, green_OR_plan_rightONred); + connect(leftlane, E, roadlets[2][0], W, (filter_fn)green_light); + connect(rightlane, E, roadlets[3][0], W, (filter_fn)green_OR_plan_rightONred); } void intersection_4x4::connectNout(roadlet *leftlane, roadlet *rightlane) { - connect(roadlets[0][2], N, leftlane, S, strait); - connect(roadlets[0][3], N, rightlane, S, strait_or_right); + connect(roadlets[0][2], N, leftlane, S,(filter_fn) strait); + connect(roadlets[0][3], N, rightlane, S, (filter_fn)strait_or_right); } void intersection_4x4::connectEout(roadlet *leftlane, roadlet *rightlane) { - connect(roadlets[2][3], E, leftlane, W, strait); - connect(roadlets[3][3], E, rightlane, W, strait_or_right); + connect(roadlets[2][3], E, leftlane, W, (filter_fn)strait); + connect(roadlets[3][3], E, rightlane, W, (filter_fn)strait_or_right); } void intersection_4x4::connectSout(roadlet *leftlane, roadlet *rightlane) { - connect(roadlets[3][1], S, leftlane, N, strait); - connect(roadlets[3][0], S, rightlane, N, strait_or_right); + connect(roadlets[3][1], S, leftlane, N, (filter_fn)strait); + connect(roadlets[3][0], S, rightlane, N, (filter_fn)strait_or_right); } void intersection_4x4::connectWout(roadlet *leftlane, roadlet *rightlane) { - connect(roadlets[1][0], W, leftlane, E, strait); - connect(roadlets[0][0], W, rightlane, E, strait_or_right); + connect(roadlets[1][0], W, leftlane, E, (filter_fn)strait); + connect(roadlets[0][0], W, rightlane, E, (filter_fn)strait_or_right); } - intersection_4x4::intersection_4x4(char *name) +intersection_4x4::intersection_4x4(char *name) { char *buff; @@ -64,7 +64,7 @@ for(i=0; i<4; i++) for(j=0; j<4; j++) { - buff = malloc(strlen(name) + 7); + buff = (char*)malloc(strlen(name) + 7); sprintf(buff, "%s %d %d", name, i, j); roadlets[i][j] = new intersection_roadlet(buff, l); } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/intersection.h Mon Oct 4 16:19:30 2004 @@ -16,12 +16,14 @@ roadlet *, direction, roadlet * (*r1_to_r2_filter_function)(roadlet *, vehicle *, direction)); +typedef roadlet * (*filter_fn)(roadlet *, vehicle *, direction); + class intersection { protected: light *the_light; public: - light *light() {return (the_light);}; + light *get_light() {return (the_light);}; }; class intersection_2x2 : public intersection Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp:1.2 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp:1.3 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp:1.2 Mon Oct 4 16:08:35 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp Mon Oct 4 16:19:30 2004 @@ -79,7 +79,7 @@ for(i=0; i< 100000; i++) { - i1.light()->tick(); + i1.get_light()->tick(); } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h:1.2 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h:1.3 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h:1.2 Mon Oct 4 16:08:35 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h Mon Oct 4 16:19:30 2004 @@ -49,7 +49,7 @@ public: intersection_roadlet(char *name, light *alight) : roadlet(name) {l = alight;} ; - light *light() { return(l);}; + light *get_light() { return(l);}; }; #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.cpp:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.cpp Mon Oct 4 16:19:30 2004 @@ -13,7 +13,7 @@ ostream& operator<<(ostream& o, vehicle v) { - o << v.name << " at " << *(v.location) << " going " << v.direction(); + o << v.name << " at " << *(v.location) << " going " << v.get_direction(); return (o); } @@ -68,7 +68,7 @@ possible_moves = location->moves(); - for(used=0, dir=N; dir<=NW; dir ++) + for(used=0, dir=N; dir<=NW; ++dir) { // cout << "possible_moves[" << dir << "] " << possible_moves[dir.as_int()] << '\n'; if (possible_moves[dir.as_int()](location->neighbor(dir), this, dir) != NULL) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.h:1.2 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.h:1.3 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.h:1.2 Mon Oct 4 16:08:35 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/vehicle.h Mon Oct 4 16:19:30 2004 @@ -30,7 +30,7 @@ int plan; - direction direction() {return (dir);}; + direction get_direction() {return (dir);}; void set_location(roadlet *r) {location = r;}; void tick(); From gaeke at cs.uiuc.edu Mon Oct 4 16:33:49 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Mon, 4 Oct 2004 16:33:49 -0500 Subject: [llvm-commits] CVS: reopt/lib/Makefile Message-ID: <200410042133.QAA21387@zion.cs.uiuc.edu> Changes in directory reopt/lib: Makefile updated: 1.24 -> 1.25 --- Log message: ScratchMemory must be built before WholeReoptimizer --- Diffs of the changes: (+1 -1) Index: reopt/lib/Makefile diff -u reopt/lib/Makefile:1.24 reopt/lib/Makefile:1.25 --- reopt/lib/Makefile:1.24 Mon Oct 4 15:15:26 2004 +++ reopt/lib/Makefile Mon Oct 4 16:33:39 2004 @@ -5,7 +5,7 @@ # Mac OS X assembler doesn't love the dummy function. ifneq ($(ARCH),PowerPC) -DIRS := $(DIRS) ScratchMemory +DIRS := ScratchMemory $(DIRS) endif include $(LEVEL)/Makefile.common From lattner at cs.uiuc.edu Mon Oct 4 16:39:50 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 16:39:50 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/build Message-ID: <200410042139.QAA15325@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/city: build (r1.1) removed --- Log message: this is unneeded --- Diffs of the changes: (+0 -0) From reid at x10sys.com Mon Oct 4 17:06:03 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 17:06:03 -0500 Subject: [llvm-commits] CVS: llvm/autoconf/configure.ac Message-ID: <200410042206.RAA02490@zion.cs.uiuc.edu> Changes in directory llvm/autoconf: configure.ac updated: 1.122 -> 1.123 --- Log message: Add checks for the ZLIB and BZIP2 header files, not just the libraries. --- Diffs of the changes: (+10 -4) Index: llvm/autoconf/configure.ac diff -u llvm/autoconf/configure.ac:1.122 llvm/autoconf/configure.ac:1.123 --- llvm/autoconf/configure.ac:1.122 Mon Oct 4 13:02:55 2004 +++ llvm/autoconf/configure.ac Mon Oct 4 17:05:53 2004 @@ -249,14 +249,20 @@ dnl Check for bzip2 and zlib compression libraries needed for archive reading/writing AC_CHECK_LIB(bz2,BZ2_bzCompressInit,[bzip2_found=1],[bzip2_found=0]) +AC_CHECK_HEADERS([bzlib.h],[bzlib_h_found=1],[bzlib_h_found=0],[]) AC_CHECK_LIB(z,gzopen,[zlib_found=1],[zlib_found=0]) -AC_SUBST([HAVE_ZLIB],$zlib_found) -AC_SUBST([HAVE_BZIP2],$bzip2_found) -if test $zlib_found -eq 1 ; then +AC_CHECK_HEADERS([zlib.h],[zlib_h_found=1],[zlib_h_found=0],[]) +if test $zlib_found -eq 1 -a $zlib_h_found -eq 1; then AC_DEFINE([HAVE_ZLIB],[1],[Define if zlib library is available on this platform.]) + AC_SUBST([HAVE_ZLIB],[1]) +else + AC_SUBST([HAVE_ZLIB],[0]) fi -if test $bzip2_found -eq 1 ; then +if test $bzip2_found -eq 1 -a $bzlib_h_found -eq 1 ; then AC_DEFINE([HAVE_BZIP2],[1],[Define if bzip2 library is available on this platform.]) + AC_SUBST([HAVE_BZIP2],[1]) +else + AC_SUBST([HAVE_BZIP2],[0]) fi dnl dlopen() is required for plugin support. AC_SEARCH_LIBS(dlopen,dl,AC_DEFINE([HAVE_DLOPEN],[1],[Define if dlopen() is available on this platform.]),AC_MSG_WARN([dlopen() not found - disabling plugin support])) From reid at x10sys.com Mon Oct 4 17:06:03 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 17:06:03 -0500 Subject: [llvm-commits] CVS: llvm/configure Message-ID: <200410042206.RAA02491@zion.cs.uiuc.edu> Changes in directory llvm: configure updated: 1.127 -> 1.128 --- Log message: Add checks for the ZLIB and BZIP2 header files, not just the libraries. --- Diffs of the changes: (+324 -13) Index: llvm/configure diff -u llvm/configure:1.127 llvm/configure:1.128 --- llvm/configure:1.127 Mon Oct 4 02:05:05 2004 +++ llvm/configure Mon Oct 4 17:05:52 2004 @@ -19269,6 +19269,158 @@ bzip2_found=0 fi + +for ac_header in bzlib.h +do +as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` +if eval "test \"\${$as_ac_Header+set}\" = set"; then + echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 +if eval "test \"\${$as_ac_Header+set}\" = set"; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +fi +echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 +echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 +else + # Is the header compilable? +echo "$as_me:$LINENO: checking $ac_header usability" >&5 +echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6 +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" + || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_header_compiler=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_header_compiler=no +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +echo "${ECHO_T}$ac_header_compiler" >&6 + +# Is the header present? +echo "$as_me:$LINENO: checking $ac_header presence" >&5 +echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6 +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include <$ac_header> +_ACEOF +if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 + (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null; then + if test -s conftest.err; then + ac_cpp_err=$ac_c_preproc_warn_flag + ac_cpp_err=$ac_cpp_err$ac_c_werror_flag + else + ac_cpp_err= + fi +else + ac_cpp_err=yes +fi +if test -z "$ac_cpp_err"; then + ac_header_preproc=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_preproc=no +fi +rm -f conftest.err conftest.$ac_ext +echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +echo "${ECHO_T}$ac_header_preproc" >&6 + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in + yes:no: ) + { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 +echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 +echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 +echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 +echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 +echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 +echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} + ( + cat <<\_ASBOX +## ----------------------------------- ## +## Report this to llvmbugs at cs.uiuc.edu ## +## ----------------------------------- ## +_ASBOX + ) | + sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac +echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 +if eval "test \"\${$as_ac_Header+set}\" = set"; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + eval "$as_ac_Header=\$ac_header_preproc" +fi +echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 +echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 + +fi +if test `eval echo '${'$as_ac_Header'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + bzlib_h_found=1 +else + bzlib_h_found=0 +fi + +done + echo "$as_me:$LINENO: checking for gzopen in -lz" >&5 echo $ECHO_N "checking for gzopen in -lz... $ECHO_C" >&6 if test "${ac_cv_lib_z_gzopen+set}" = set; then @@ -19339,34 +19491,182 @@ zlib_found=0 fi -HAVE_ZLIB=$zlib_found -HAVE_BZIP2=$bzip2_found +for ac_header in zlib.h +do +as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` +if eval "test \"\${$as_ac_Header+set}\" = set"; then + echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 +if eval "test \"\${$as_ac_Header+set}\" = set"; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +fi +echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 +echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 +else + # Is the header compilable? +echo "$as_me:$LINENO: checking $ac_header usability" >&5 +echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6 +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && + { ac_try='test -z "$ac_c_werror_flag" + || test ! -s conftest.err' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; } && + { ac_try='test -s conftest.$ac_objext' + { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 + (eval $ac_try) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_header_compiler=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +ac_header_compiler=no +fi +rm -f conftest.err conftest.$ac_objext conftest.$ac_ext +echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +echo "${ECHO_T}$ac_header_compiler" >&6 + +# Is the header present? +echo "$as_me:$LINENO: checking $ac_header presence" >&5 +echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6 +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include <$ac_header> +_ACEOF +if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 + (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null; then + if test -s conftest.err; then + ac_cpp_err=$ac_c_preproc_warn_flag + ac_cpp_err=$ac_cpp_err$ac_c_werror_flag + else + ac_cpp_err= + fi +else + ac_cpp_err=yes +fi +if test -z "$ac_cpp_err"; then + ac_header_preproc=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_preproc=no +fi +rm -f conftest.err conftest.$ac_ext +echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +echo "${ECHO_T}$ac_header_preproc" >&6 + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in + yes:no: ) + { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 +echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 +echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 +echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 +echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 +echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 +echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} + ( + cat <<\_ASBOX +## ----------------------------------- ## +## Report this to llvmbugs at cs.uiuc.edu ## +## ----------------------------------- ## +_ASBOX + ) | + sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac +echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 +if eval "test \"\${$as_ac_Header+set}\" = set"; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + eval "$as_ac_Header=\$ac_header_preproc" +fi +echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 +echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 + +fi +if test `eval echo '${'$as_ac_Header'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + zlib_h_found=1 +else + zlib_h_found=0 +fi -if test $zlib_found -eq 1 ; then +done + +if test $zlib_found -eq 1 -a $zlib_h_found -eq 1; then cat >>confdefs.h <<\_ACEOF #define HAVE_ZLIB 1 _ACEOF + HAVE_ZLIB=1 + +else + HAVE_ZLIB=0 + fi -if test $bzip2_found -eq 1 ; then +if test $bzip2_found -eq 1 -a $bzlib_h_found -eq 1 ; then cat >>confdefs.h <<\_ACEOF #define HAVE_BZIP2 1 _ACEOF + HAVE_BZIP2=1 + else - if test $zlib_found -ne 1 ; then - { echo "$as_me:$LINENO: WARNING: **** Neither zlib nor bzip2 compression libraries were found - - archives will not support compression! Install bzip2 or zlib - and then reconfigure to ensure compatibility" >&5 -echo "$as_me: WARNING: **** Neither zlib nor bzip2 compression libraries were found - - archives will not support compression! Install bzip2 or zlib - and then reconfigure to ensure compatibility" >&2;} - fi -fi + HAVE_BZIP2=0 +fi echo "$as_me:$LINENO: checking for library containing dlopen" >&5 echo $ECHO_N "checking for library containing dlopen... $ECHO_C" >&6 if test "${ac_cv_search_dlopen+set}" = set; then @@ -25815,6 +26115,17 @@ fi +if test $bzip2_found -ne 1 ; then + if test $zlib_found -ne 1 ; then + { echo "$as_me:$LINENO: WARNING: *** Neither zlib nor bzip2 compression libraries were found." >&5 +echo "$as_me: WARNING: *** Neither zlib nor bzip2 compression libraries were found." >&2;} + { echo "$as_me:$LINENO: WARNING: *** Bytecode archives will not support compression!" >&5 +echo "$as_me: WARNING: *** Bytecode archives will not support compression!" >&2;} + { echo "$as_me:$LINENO: WARNING: *** To correct, install the libraries and and re-run configure." >&5 +echo "$as_me: WARNING: *** To correct, install the libraries and and re-run configure." >&2;} + fi +fi + if test $llvmgccwarn = yes then { echo "$as_me:$LINENO: WARNING: ***** llvm C/C++ front end was not found, or does not" >&5 From lattner at cs.uiuc.edu Mon Oct 4 19:18:34 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:18:34 -0500 Subject: [llvm-commits] CVS: llvm/test/Regression/C++Frontend/2004-10-04-ExternalGlobalConstant.cpp.tr Message-ID: <200410050018.TAA19592@apoc.cs.uiuc.edu> Changes in directory llvm/test/Regression/C++Frontend: 2004-10-04-ExternalGlobalConstant.cpp.tr added (r1.1) --- Log message: New testcase for PR450: http://llvm.cs.uiuc.edu/PR450 --- Diffs of the changes: (+12 -0) Index: llvm/test/Regression/C++Frontend/2004-10-04-ExternalGlobalConstant.cpp.tr diff -c /dev/null llvm/test/Regression/C++Frontend/2004-10-04-ExternalGlobalConstant.cpp.tr:1.1 *** /dev/null Mon Oct 4 19:18:31 2004 --- llvm/test/Regression/C++Frontend/2004-10-04-ExternalGlobalConstant.cpp.tr Mon Oct 4 19:18:21 2004 *************** *** 0 **** --- 1,12 ---- + // RUN: %llvmgcc -xc++ -S -o - %s | grep %y | not grep constant + + struct Y { + int A; + Y(); + }; + + // This global cannot be marked 'constant' because the ctor can modify it. + extern const Y y; + + void foo(...); + int bar() { foo(&y); } From lattner at cs.uiuc.edu Mon Oct 4 19:19:31 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:19:31 -0500 Subject: [llvm-commits] CVS: llvm-gcc/gcc/llvm-expand.c Message-ID: <200410050019.TAA19600@apoc.cs.uiuc.edu> Changes in directory llvm-gcc/gcc: llvm-expand.c updated: 1.50 -> 1.51 --- Log message: External globals with ctors cannot be marked LLVM constant. This fixes PR450: http://llvm.cs.uiuc.edu/PR450 , testcase test/Regression/C++Frontend/2004-10-04-ExternalGlobalConstant.cpp.tr, and the Prolangs-C++/city program. --- Diffs of the changes: (+13 -5) Index: llvm-gcc/gcc/llvm-expand.c diff -u llvm-gcc/gcc/llvm-expand.c:1.50 llvm-gcc/gcc/llvm-expand.c:1.51 --- llvm-gcc/gcc/llvm-expand.c:1.50 Fri Jul 16 21:30:05 2004 +++ llvm-gcc/gcc/llvm-expand.c Mon Oct 4 19:19:18 2004 @@ -7099,11 +7099,19 @@ } else if (*/DECL_WEAK(decl) || DECL_COMMON(decl) || DECL_VIRTUAL_P(decl)) G->Linkage = L_Weak; - if (TREE_READONLY(decl) && !TREE_SIDE_EFFECTS(decl) && - (DECL_EXTERNAL(decl) || - (DECL_INITIAL(decl) != error_mark_node && /* no ctor? */ - DECL_INITIAL(decl) && TREE_CONSTANT(DECL_INITIAL(decl))))) - G->isConstant = 1; + if (TREE_READONLY(decl) && !TREE_SIDE_EFFECTS(decl)) { + if (DECL_EXTERNAL(decl)) { + /* Mark external globals constant only if they are lacking ctors/dtors. + */ + if (!TYPE_NEEDS_CONSTRUCTING(TREE_TYPE(decl))) + G->isConstant = 1; + } else { + /* Mark readonly globals with constant initializes constant. */ + if (DECL_INITIAL(decl) != error_mark_node && /* uninitialized? */ + DECL_INITIAL(decl) && TREE_CONSTANT(DECL_INITIAL(decl))) + G->isConstant = 1; + } + } /* Allociate the LLVM global with the tree global */ SET_DECL_LLVM(decl, G2V(G)); From lattner at cs.uiuc.edu Mon Oct 4 19:23:13 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:23:13 -0500 Subject: [llvm-commits] CVS: llvm/docs/ReleaseNotes.html Message-ID: <200410050023.TAA19628@apoc.cs.uiuc.edu> Changes in directory llvm/docs: ReleaseNotes.html updated: 1.240 -> 1.241 --- Log message: Bug fixed --- Diffs of the changes: (+3 -1) Index: llvm/docs/ReleaseNotes.html diff -u llvm/docs/ReleaseNotes.html:1.240 llvm/docs/ReleaseNotes.html:1.241 --- llvm/docs/ReleaseNotes.html:1.240 Mon Sep 27 22:45:22 2004 +++ llvm/docs/ReleaseNotes.html Mon Oct 4 19:23:02 2004 @@ -174,6 +174,8 @@
    1. [llvmg++] not enough templates are instantiated
    2. +
    3. [llvmg++] Extern const globals cannot be +marked 'constant' if they have nontrivial ctors or dtors

    Bugs fixed in the Sparc V9 back-end:

    @@ -617,7 +619,7 @@ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /> The LLVM Compiler Infrastructure
    - Last modified: $Date: 2004/09/28 03:45:22 $ + Last modified: $Date: 2004/10/05 00:23:02 $ From lattner at cs.uiuc.edu Mon Oct 4 19:23:38 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:23:38 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.3/docs/ReleaseNotes.html Message-ID: <200410050023.TAA19647@apoc.cs.uiuc.edu> Changes in directory llvm-www/releases/1.3/docs: ReleaseNotes.html updated: 1.7 -> 1.8 --- Log message: Bug found --- Diffs of the changes: (+4 -1) Index: llvm-www/releases/1.3/docs/ReleaseNotes.html diff -u llvm-www/releases/1.3/docs/ReleaseNotes.html:1.7 llvm-www/releases/1.3/docs/ReleaseNotes.html:1.8 --- llvm-www/releases/1.3/docs/ReleaseNotes.html:1.7 Mon Sep 27 22:45:08 2004 +++ llvm-www/releases/1.3/docs/ReleaseNotes.html Mon Oct 4 19:23:28 2004 @@ -483,6 +483,9 @@ Bugs in 1.3 fixed in 1.4: @@ -786,7 +789,7 @@ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /> The LLVM Compiler Infrastructure
    - Last modified: $Date: 2004/09/28 03:45:08 $ + Last modified: $Date: 2004/10/05 00:23:28 $ From lattner at cs.uiuc.edu Mon Oct 4 19:29:12 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:29:12 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp roadlet.cpp roadlet.h Message-ID: <200410050029.TAA19684@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/city: main.cpp updated: 1.3 -> 1.4 roadlet.cpp updated: 1.2 -> 1.3 roadlet.h updated: 1.3 -> 1.4 --- Log message: Finish making this work, woo... --- Diffs of the changes: (+13 -5) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp:1.3 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp:1.4 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp:1.3 Mon Oct 4 16:19:30 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp Mon Oct 4 19:29:01 2004 @@ -71,13 +71,13 @@ broken_light l(3,1,4,1); - for(i = 0; i < 100000; i++) + for(i = 0; i < 100; i++) { cout << l << "\n"; l.tick(); } - for(i=0; i< 100000; i++) + for(i=0; i< 100; i++) { i1.get_light()->tick(); } @@ -94,7 +94,7 @@ i1.connectEout(r3, r1); - for(i=0; i< 100000; i++) + for(i=0; i< 100; i++) { cout << '\n' << i << ' ' << c << '\n'; c.tick(); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.cpp:1.2 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.cpp:1.3 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.cpp:1.2 Mon Oct 4 16:08:35 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.cpp Mon Oct 4 19:29:01 2004 @@ -5,6 +5,10 @@ void roadlet::init(char *n) { + occupant = 0; + neighbors[0] = neighbors[1] = neighbors[2] = neighbors[3] = 0; + neighbors[4] = neighbors[5] = neighbors[6] = neighbors[7] = 0; + name = n; for(int i=0;i<8;i++) the_moves[i] = return_null; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h:1.3 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h:1.4 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h:1.3 Mon Oct 4 16:19:30 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/roadlet.h Mon Oct 4 19:29:01 2004 @@ -24,8 +24,12 @@ move_function the_moves[8]; public: - roadlet() : occupant(NULL) { neighbors[0] = neighbors[1] = neighbors[2] = neighbors[3] = neighbors[4] = neighbors[5] = neighbors[6] = neighbors[7] = 0; init("unnamed");}; - roadlet(char *n) { init(n);}; + roadlet() { + init("unnamed"); + }; + roadlet(char *n) { + init(n); + }; int occupied() { return(occupiedby() != NULL);}; vehicle *occupiedby() {return(occupant);}; void arrive(vehicle *v) {occupant = v;}; From lattner at cs.uiuc.edu Mon Oct 4 19:30:32 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:30:32 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp Message-ID: <200410050030.TAA19919@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/city: main.cpp updated: 1.4 -> 1.5 --- Log message: Return back to a reasonable running time --- Diffs of the changes: (+3 -3) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp:1.4 llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp:1.5 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp:1.4 Mon Oct 4 19:29:01 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/main.cpp Mon Oct 4 19:30:21 2004 @@ -71,13 +71,13 @@ broken_light l(3,1,4,1); - for(i = 0; i < 100; i++) + for(i = 0; i < 100000; i++) { cout << l << "\n"; l.tick(); } - for(i=0; i< 100; i++) + for(i=0; i< 100000; i++) { i1.get_light()->tick(); } @@ -94,7 +94,7 @@ i1.connectEout(r3, r1); - for(i=0; i< 100; i++) + for(i=0; i< 100000; i++) { cout << '\n' << i << ' ' << c << '\n'; c.tick(); From lattner at cs.uiuc.edu Mon Oct 4 19:33:25 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:33:25 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/Makefile student2.cpp student2.h Message-ID: <200410050033.TAA20172@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1: Makefile added (r1.1) student2.cpp updated: 1.1 -> 1.2 student2.h updated: 1.1 -> 1.2 --- Log message: Make this compile and work --- Diffs of the changes: (+9 -2) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/Makefile:1.1 *** /dev/null Mon Oct 4 19:33:24 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/Makefile Mon Oct 4 19:33:14 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = deriv1 + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.cpp:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.cpp Mon Oct 4 19:33:14 2004 @@ -1,7 +1,8 @@ // Written for undergraduate C++ course project at Dept of // Computer Science, Rutgers University. -#include +#include +using namespace std; #include #include "student2.h" void bin_op_expr::print_me() Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv1/student2.h Mon Oct 4 19:33:14 2004 @@ -49,7 +49,7 @@ private: char *name; public: - var_expr(strng str) {strcpy(name,str);} + var_expr(strng str) {name = strdup(str);} /* Copy the initialization string into the name buffer. To read the documentation for strcpy() and other C string manipulation functions, From lattner at cs.uiuc.edu Mon Oct 4 19:33:35 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:33:35 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/Makefile Message-ID: <200410050033.TAA20183@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/city: Makefile added (r1.1) --- Log message: Right, add the makefile --- Diffs of the changes: (+6 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/Makefile:1.1 *** /dev/null Mon Oct 4 19:33:34 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/city/Makefile Mon Oct 4 19:33:24 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = city + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + From lattner at cs.uiuc.edu Mon Oct 4 19:35:47 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:35:47 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/Makefile Message-ID: <200410050035.TAA20296@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2: Makefile added (r1.1) --- Log message: Makefilify --- Diffs of the changes: (+6 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/Makefile:1.1 *** /dev/null Mon Oct 4 19:35:46 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/Makefile Mon Oct 4 19:35:36 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = deriv2 + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + From lattner at cs.uiuc.edu Mon Oct 4 19:36:06 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:36:06 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/student3.cpp Message-ID: <200410050036.TAA20314@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2: student3.cpp updated: 1.1 -> 1.2 --- Log message: Compile --- Diffs of the changes: (+2 -1) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/student3.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/student3.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/student3.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/student3.cpp:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/deriv2/student3.cpp Mon Oct 4 19:35:25 2004 @@ -1,7 +1,8 @@ // Written for undergraduate C++ course project at Dept of // Computer Science, Rutgers University. -#include +#include #include +using namespace std; #include "student3.h" // evaluation of a constant is the value of the constant. double const_expr::eval(double numb) From lattner at cs.uiuc.edu Mon Oct 4 19:37:43 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:37:43 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/boss.h commission.h company.h employee.h hourly-no-over.h hourly-over.h hourly.h piece.h wage.h Message-ID: <200410050037.TAA20383@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ: boss.h updated: 1.1 -> 1.2 commission.h updated: 1.1 -> 1.2 company.h updated: 1.1 -> 1.2 employee.h updated: 1.1 -> 1.2 hourly-no-over.h updated: 1.1 -> 1.2 hourly-over.h updated: 1.1 -> 1.2 hourly.h updated: 1.1 -> 1.2 piece.h updated: 1.1 -> 1.2 wage.h updated: 1.1 -> 1.2 --- Log message: Stop using deprecated headers --- Diffs of the changes: (+68 -28) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/boss.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/boss.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/boss.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/boss.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/boss.h Mon Oct 4 19:37:32 2004 @@ -17,10 +17,13 @@ ** RCS : ** ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/boss.h,v $ -** $Revision: 1.1 $ -** $Date: 2004/10/04 20:01:13 $ +** $Revision: 1.2 $ +** $Date: 2004/10/05 00:37:32 $ ** ** $Log: boss.h,v $ +** Revision 1.2 2004/10/05 00:37:32 lattner +** Stop using deprecated headers +** ** Revision 1.1 2004/10/04 20:01:13 lattner ** Initial checkin of all of the source ** @@ -40,7 +43,9 @@ #define BOSS_ID 1 -#include +#include +using namespace std; + /* A boss gets a weekly salary, regardless of how much (s)he works */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h Mon Oct 4 19:37:32 2004 @@ -17,10 +17,13 @@ ** RCS : ** ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h,v $ -** $Revision: 1.1 $ -** $Date: 2004/10/04 20:01:13 $ +** $Revision: 1.2 $ +** $Date: 2004/10/05 00:37:32 $ ** ** $Log: commission.h,v $ +** Revision 1.2 2004/10/05 00:37:32 lattner +** Stop using deprecated headers +** ** Revision 1.1 2004/10/04 20:01:13 lattner ** Initial checkin of all of the source ** @@ -38,8 +41,9 @@ #include "employee.h" -#include +#include #include +using namespace std; #define COMMISSIONED_WORKER_ID 2 /* A commissioned worker gets a weekly salary + commission per quantity sold */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h Mon Oct 4 19:37:32 2004 @@ -12,10 +12,13 @@ ** RCS : ** ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h,v $ -** $Revision: 1.1 $ -** $Date: 2004/10/04 20:01:13 $ +** $Revision: 1.2 $ +** $Date: 2004/10/05 00:37:32 $ ** ** $Log: company.h,v $ +** Revision 1.2 2004/10/05 00:37:32 lattner +** Stop using deprecated headers +** ** Revision 1.1 2004/10/04 20:01:13 lattner ** Initial checkin of all of the source ** @@ -30,7 +33,9 @@ #include "employee.h" -#include +#include +using namespace std; + class EmployeeNode { Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/employee.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/employee.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/employee.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/employee.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/employee.h Mon Oct 4 19:37:32 2004 @@ -17,10 +17,13 @@ ** RCS : ** ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/employee.h,v $ -** $Revision: 1.1 $ -** $Date: 2004/10/04 20:01:13 $ +** $Revision: 1.2 $ +** $Date: 2004/10/05 00:37:32 $ ** ** $Log: employee.h,v $ +** Revision 1.2 2004/10/05 00:37:32 lattner +** Stop using deprecated headers +** ** Revision 1.1 2004/10/04 20:01:13 lattner ** Initial checkin of all of the source ** @@ -33,8 +36,9 @@ #ifndef _EMPLOYEE_H #define _EMPLOYEE_H -#include -#include +#include +#include +using namespace std; #define EMPLOYEE_ID 0 Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-no-over.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-no-over.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-no-over.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-no-over.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-no-over.h Mon Oct 4 19:37:32 2004 @@ -17,10 +17,13 @@ ** RCS : ** ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-no-over.h,v $ -** $Revision: 1.1 $ -** $Date: 2004/10/04 20:01:13 $ +** $Revision: 1.2 $ +** $Date: 2004/10/05 00:37:32 $ ** ** $Log: hourly-no-over.h,v $ +** Revision 1.2 2004/10/05 00:37:32 lattner +** Stop using deprecated headers +** ** Revision 1.1 2004/10/04 20:01:13 lattner ** Initial checkin of all of the source ** @@ -35,8 +38,10 @@ #include "hourly.h" -#include +#include #include +using namespace std; + #define HOURLY_WORKER_NO_OVERTIME_ID 7 Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-over.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-over.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-over.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-over.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-over.h Mon Oct 4 19:37:32 2004 @@ -17,10 +17,13 @@ ** RCS : ** ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly-over.h,v $ -** $Revision: 1.1 $ -** $Date: 2004/10/04 20:01:13 $ +** $Revision: 1.2 $ +** $Date: 2004/10/05 00:37:32 $ ** ** $Log: hourly-over.h,v $ +** Revision 1.2 2004/10/05 00:37:32 lattner +** Stop using deprecated headers +** ** Revision 1.1 2004/10/04 20:01:13 lattner ** Initial checkin of all of the source ** @@ -35,8 +38,9 @@ #include "hourly.h" -#include +#include #include +using namespace std; #define HOURLY_WORKER_OVERTIME_ID 6 /* An hourly worker overtime gets paid for every hour worked, and time and Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly.h Mon Oct 4 19:37:32 2004 @@ -17,10 +17,13 @@ ** RCS : ** ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/hourly.h,v $ -** $Revision: 1.1 $ -** $Date: 2004/10/04 20:01:13 $ +** $Revision: 1.2 $ +** $Date: 2004/10/05 00:37:32 $ ** ** $Log: hourly.h,v $ +** Revision 1.2 2004/10/05 00:37:32 lattner +** Stop using deprecated headers +** ** Revision 1.1 2004/10/04 20:01:13 lattner ** Initial checkin of all of the source ** @@ -39,8 +42,10 @@ #include "wage.h" #define HOURLY_ID 5 -#include +#include #include +using namespace std; + /* An hourly worker gets paid for every hour worked */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/piece.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/piece.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/piece.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/piece.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/piece.h Mon Oct 4 19:37:32 2004 @@ -17,10 +17,13 @@ ** RCS : ** ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/piece.h,v $ -** $Revision: 1.1 $ -** $Date: 2004/10/04 20:01:13 $ +** $Revision: 1.2 $ +** $Date: 2004/10/05 00:37:32 $ ** ** $Log: piece.h,v $ +** Revision 1.2 2004/10/05 00:37:32 lattner +** Stop using deprecated headers +** ** Revision 1.1 2004/10/04 20:01:13 lattner ** Initial checkin of all of the source ** @@ -39,7 +42,8 @@ #include "wage.h" #define PIECE_WORKER_ID 4 -#include +#include +using namespace std; /* A piece worker gets paid for every item produced */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/wage.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/wage.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/wage.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/wage.h:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/wage.h Mon Oct 4 19:37:32 2004 @@ -17,10 +17,13 @@ ** RCS : ** ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/wage.h,v $ -** $Revision: 1.1 $ -** $Date: 2004/10/04 20:01:13 $ +** $Revision: 1.2 $ +** $Date: 2004/10/05 00:37:32 $ ** ** $Log: wage.h,v $ +** Revision 1.2 2004/10/05 00:37:32 lattner +** Stop using deprecated headers +** ** Revision 1.1 2004/10/04 20:01:13 lattner ** Initial checkin of all of the source ** @@ -37,8 +40,9 @@ #define WAGE_WORKER_ID 3 -#include +#include #include +using namespace std; /* A wage worker gets paid for every (item, hour, etc) worked/produced */ From lattner at cs.uiuc.edu Mon Oct 4 19:38:57 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:38:57 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h Message-ID: <200410050038.TAA20511@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ: company.h updated: 1.2 -> 1.3 --- Log message: Methods cannot be named the same thing classes are --- Diffs of the changes: (+9 -6) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h:1.2 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h:1.3 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h:1.2 Mon Oct 4 19:37:32 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h Mon Oct 4 19:38:46 2004 @@ -12,10 +12,13 @@ ** RCS : ** ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/company.h,v $ -** $Revision: 1.2 $ -** $Date: 2004/10/05 00:37:32 $ +** $Revision: 1.3 $ +** $Date: 2004/10/05 00:38:46 $ ** ** $Log: company.h,v $ +** Revision 1.3 2004/10/05 00:38:46 lattner +** Methods cannot be named the same thing classes are +** ** Revision 1.2 2004/10/05 00:37:32 lattner ** Stop using deprecated headers ** @@ -46,7 +49,7 @@ public: EmployeeNode(Employee *, EmployeeNode *); - Employee * Employee() { return employee; } + Employee * getEmployee() { return employee; } EmployeeNode * Next(); }; /*****************************************************************************/ @@ -108,7 +111,7 @@ EmployeeNode * curE; for(curE = employeeList; curE != NULL; curE = curE->Next()) - curE->Employee()->PrintWithEarnings(currentWeek); + curE->getEmployee()->PrintWithEarnings(currentWeek); } /*****************************************************************************/ void @@ -119,7 +122,7 @@ currentWeek++; for(curE = employeeList; curE != NULL; curE = curE->Next()) - curE->Employee()->NewWeek(); + curE->getEmployee()->NewWeek(); } /*****************************************************************************/ void @@ -128,7 +131,7 @@ EmployeeNode * curE; for(curE = employeeList; curE != NULL; curE = curE->Next()) - curE->Employee()->Raise(units); + curE->getEmployee()->Raise(units); } #endif From lattner at cs.uiuc.edu Mon Oct 4 19:41:30 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:41:30 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/driver.cpp Message-ID: <200410050041.TAA20601@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ: driver.cpp updated: 1.1 -> 1.2 --- Log message: Don't print argv[0] --- Diffs of the changes: (+6 -3) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/driver.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/driver.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/driver.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/driver.cpp:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/driver.cpp Mon Oct 4 19:41:19 2004 @@ -12,10 +12,13 @@ ** RCS : ** ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/driver.cpp,v $ -** $Revision: 1.1 $ -** $Date: 2004/10/04 20:01:13 $ +** $Revision: 1.2 $ +** $Date: 2004/10/05 00:41:19 $ ** ** $Log: driver.cpp,v $ +** Revision 1.2 2004/10/05 00:41:19 lattner +** Don't print argv[0] +** ** Revision 1.1 2004/10/04 20:01:13 lattner ** Initial checkin of all of the source ** @@ -45,7 +48,7 @@ Company * c; if (argc != 2) { - fprintf(stderr, "usage: %s \n", argv[0]); + fprintf(stderr, "usage: %s \n", "employ"); return 1; } From lattner at cs.uiuc.edu Mon Oct 4 19:42:07 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:42:07 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/build Message-ID: <200410050042.TAA20616@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ: build (r1.1) removed --- Log message: We don't need this --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 19:46:32 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:46:32 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/Unix/MappedFile.cpp Message-ID: <200410050046.TAA20905@apoc.cs.uiuc.edu> Changes in directory llvm/lib/System/Unix: MappedFile.cpp updated: 1.1 -> 1.2 --- Log message: Solaris doesn't have MAP_FILE. --- Diffs of the changes: (+4 -1) Index: llvm/lib/System/Unix/MappedFile.cpp diff -u llvm/lib/System/Unix/MappedFile.cpp:1.1 llvm/lib/System/Unix/MappedFile.cpp:1.2 --- llvm/lib/System/Unix/MappedFile.cpp:1.1 Mon Oct 4 06:08:32 2004 +++ llvm/lib/System/Unix/MappedFile.cpp Mon Oct 4 19:46:21 2004 @@ -76,7 +76,10 @@ void* MappedFile::map() { if (!isMapped()) { int prot = PROT_NONE; - int flags = MAP_FILE; + int flags = 0; +#ifdef MAP_FILE + flags |= MAP_FILE; +#endif if (options_ == 0) { prot = PROT_READ; flags = MAP_PRIVATE; From lattner at cs.uiuc.edu Mon Oct 4 19:46:54 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:46:54 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/input.txt Message-ID: <200410050046.TAA20919@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ: input.txt added (r1.1) --- Log message: New data file --- Diffs of the changes: (+3 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/input.txt diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/input.txt:1.1 *** /dev/null Mon Oct 4 19:46:54 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/input.txt Mon Oct 4 19:46:44 2004 *************** *** 0 **** --- 1,3 ---- + 1 bob jones 123.00 + 2 john doe 1232.2 + From lattner at cs.uiuc.edu Mon Oct 4 19:48:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:48:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/Makefile Message-ID: <200410050048.TAA21040@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ: Makefile added (r1.1) --- Log message: Build this --- Diffs of the changes: (+8 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/Makefile:1.1 *** /dev/null Mon Oct 4 19:47:59 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/Makefile Mon Oct 4 19:47:49 2004 *************** *** 0 **** --- 1,8 ---- + LEVEL = ../../../.. + + PROG = employ + LDFLAGS = -lstdc++ + RUN_OPTIONS = 40 + STDIN_FILENAME = input.txt + include $(LEVEL)/MultiSource/Makefile.multisrc + From tbrethou at cs.uiuc.edu Mon Oct 4 19:51:41 2004 From: tbrethou at cs.uiuc.edu (Tanya Brethour) Date: Mon, 4 Oct 2004 19:51:41 -0500 (CDT) Subject: [llvm-commits] CVS: llvm/lib/System/Unix/MappedFile.cpp Unix.h Message-ID: <200410050051.TAA15697@seraph.cs.uiuc.edu> Changes in directory llvm/lib/System/Unix: MappedFile.cpp updated: 1.2 -> 1.3 Unix.h updated: 1.5 -> 1.6 --- Log message: Added a couple of includes to get this to compile on Sparc. --- Diffs of the changes: (+2 -1) Index: llvm/lib/System/Unix/MappedFile.cpp diff -u llvm/lib/System/Unix/MappedFile.cpp:1.2 llvm/lib/System/Unix/MappedFile.cpp:1.3 --- llvm/lib/System/Unix/MappedFile.cpp:1.2 Mon Oct 4 19:46:21 2004 +++ llvm/lib/System/Unix/MappedFile.cpp Mon Oct 4 19:51:26 2004 @@ -18,7 +18,7 @@ #include "llvm/System/Process.h" #include "Unix.h" -#include +#include #include namespace llvm { Index: llvm/lib/System/Unix/Unix.h diff -u llvm/lib/System/Unix/Unix.h:1.5 llvm/lib/System/Unix/Unix.h:1.6 --- llvm/lib/System/Unix/Unix.h:1.5 Wed Sep 1 17:55:35 2004 +++ llvm/lib/System/Unix/Unix.h Mon Oct 4 19:51:26 2004 @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include From reid at x10sys.com Mon Oct 4 19:56:57 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 19:56:57 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/Unix/Unix.h Message-ID: <200410050056.TAA04936@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/Unix: Unix.h updated: 1.6 -> 1.7 --- Log message: Adjust sys/stat.h inclusion so its only for SunOS. --- Diffs of the changes: (+0 -1) Index: llvm/lib/System/Unix/Unix.h diff -u llvm/lib/System/Unix/Unix.h:1.6 llvm/lib/System/Unix/Unix.h:1.7 --- llvm/lib/System/Unix/Unix.h:1.6 Mon Oct 4 19:51:26 2004 +++ llvm/lib/System/Unix/Unix.h Mon Oct 4 19:56:46 2004 @@ -23,7 +23,6 @@ #include #include #include -#include #include #include #include From reid at x10sys.com Mon Oct 4 19:56:57 2004 From: reid at x10sys.com (Reid Spencer) Date: Mon, 4 Oct 2004 19:56:57 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/SunOS/MappedFile.cpp Message-ID: <200410050056.TAA04933@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/SunOS: MappedFile.cpp updated: 1.1 -> 1.2 --- Log message: Adjust sys/stat.h inclusion so its only for SunOS. --- Diffs of the changes: (+1 -0) Index: llvm/lib/System/SunOS/MappedFile.cpp diff -u llvm/lib/System/SunOS/MappedFile.cpp:1.1 llvm/lib/System/SunOS/MappedFile.cpp:1.2 --- llvm/lib/System/SunOS/MappedFile.cpp:1.1 Mon Oct 4 06:08:32 2004 +++ llvm/lib/System/SunOS/MappedFile.cpp Mon Oct 4 19:56:46 2004 @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// // Include the generic unix implementation +#include #include "../Unix/MappedFile.cpp" // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab From lattner at cs.uiuc.edu Mon Oct 4 19:58:01 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 19:58:01 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/Makefile commission.h input.txt Message-ID: <200410050058.TAA21455@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ: Makefile updated: 1.1 -> 1.2 commission.h updated: 1.2 -> 1.3 input.txt updated: 1.1 -> 1.2 --- Log message: Don't use unitiialized values --- Diffs of the changes: (+9 -4) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/Makefile diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/Makefile:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/Makefile:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/Makefile:1.1 Mon Oct 4 19:47:49 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/Makefile Mon Oct 4 19:57:47 2004 @@ -2,7 +2,7 @@ PROG = employ LDFLAGS = -lstdc++ -RUN_OPTIONS = 40 +RUN_OPTIONS = 400 STDIN_FILENAME = input.txt include $(LEVEL)/MultiSource/Makefile.multisrc Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h:1.2 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h:1.3 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h:1.2 Mon Oct 4 19:37:32 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h Mon Oct 4 19:57:47 2004 @@ -17,10 +17,13 @@ ** RCS : ** ** $Source: /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/commission.h,v $ -** $Revision: 1.2 $ -** $Date: 2004/10/05 00:37:32 $ +** $Revision: 1.3 $ +** $Date: 2004/10/05 00:57:47 $ ** ** $Log: commission.h,v $ +** Revision 1.3 2004/10/05 00:57:47 lattner +** Don't use unitiialized values +** ** Revision 1.2 2004/10/05 00:37:32 lattner ** Stop using deprecated headers ** @@ -72,6 +75,7 @@ float startSalary, float startCommission) : Employee(first, last) // this will call Employee's constructor { + thisWeekSales = 0; SetWeeklySalary(startSalary); SetCommissionRate(startCommission); dollarsToRaise = 10.0; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/input.txt diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/input.txt:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/input.txt:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/input.txt:1.1 Mon Oct 4 19:46:44 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/employ/input.txt Mon Oct 4 19:57:47 2004 @@ -1,3 +1,4 @@ 1 bob jones 123.00 -2 john doe 1232.2 +2 john doe 1232.2 10.21 +0 jane green 1231.123 From lattner at cs.uiuc.edu Mon Oct 4 20:00:08 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 20:00:08 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/Makefile family.cpp Message-ID: <200410050100.UAA21716@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/family: Makefile added (r1.1) family.cpp updated: 1.1 -> 1.2 --- Log message: Make this "benchmark" work --- Diffs of the changes: (+11 -5) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/Makefile:1.1 *** /dev/null Mon Oct 4 20:00:05 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/Makefile Mon Oct 4 19:59:55 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = family + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/family.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/family.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/family.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/family.cpp:1.1 Mon Oct 4 15:01:13 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/family/family.cpp Mon Oct 4 19:59:55 2004 @@ -1,8 +1,8 @@ // Listings 7.1 and 7.2 from "The C++ Workbook" by Wiener and Pinson. // Addison-Wesley 1990. -void strcpy(char *nam1, char *nam2) {*nam1 = *nam2;} -int strlen(char *nam1) { return 0;} +#include +#include class Parent { protected: @@ -31,7 +31,7 @@ } virtual void answerName(void) { - lastName; + printf("%s\n", lastName); } ~Parent(void) { @@ -74,7 +74,7 @@ virtual void answerName(void) { Parent::answerName(); - firstName; + printf("%s\n", firstName); } }; @@ -92,7 +92,7 @@ virtual void answerName(void) { Child::answerName(); - grandFatherName; + printf("GCN: %s\n", grandFatherName); } }; From lattner at cs.uiuc.edu Mon Oct 4 20:06:31 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 20:06:31 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/fsm.cpp Message-ID: <200410050106.UAA22152@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm: fsm.cpp updated: 1.1 -> 1.2 --- Log message: Make this sorta work --- Diffs of the changes: (+5 -5) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/fsm.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/fsm.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/fsm.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/fsm.cpp:1.1 Mon Oct 4 15:01:14 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/fsm.cpp Mon Oct 4 20:06:18 2004 @@ -44,8 +44,8 @@ max_node = e->to; } graph = new state[max_node+1]; // was new state[max_node+1] - for (e=p; e->from; ++e) - graph[e->from].transition[e->input] = &graph[e->to]; + for (triple *e=p; e->from; ++e) + graph[e->from].transition[(int)e->input] = &graph[e->to]; current = 0; } @@ -59,7 +59,7 @@ void fsm::advance(char x) { if (current) - current = current->transition[x]; + current = current->transition[(int)x]; } int fsm::end_state() { @@ -76,14 +76,14 @@ sample(); }; -triple sample::edges[] = {{1,'A',2}, {1, 'B', 3}}; +triple sample::edges[3] = {{1,2,'A'}, {1, 3, 'B'}}; sample::sample() : fsm(edges) { } #include -main() { +int main() { char input_string[80]; printf("Enter input expression: "); scanf("%s", input_string); From lattner at cs.uiuc.edu Mon Oct 4 21:12:33 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 21:12:33 -0500 Subject: [llvm-commits] CVS: llvm/test/Regression/Linker/ConstantGlobals1.ll ConstantGlobals2.ll Message-ID: <200410050212.VAA22403@apoc.cs.uiuc.edu> Changes in directory llvm/test/Regression/Linker: ConstantGlobals1.ll added (r1.1) ConstantGlobals2.ll added (r1.1) --- Log message: Testcase to ensure that the 'constant' flag follows the definition when there is a question. --- Diffs of the changes: (+14 -0) Index: llvm/test/Regression/Linker/ConstantGlobals1.ll diff -c /dev/null llvm/test/Regression/Linker/ConstantGlobals1.ll:1.1 *** /dev/null Mon Oct 4 21:12:30 2004 --- llvm/test/Regression/Linker/ConstantGlobals1.ll Mon Oct 4 21:12:20 2004 *************** *** 0 **** --- 1,7 ---- + ; Test that appending linkage works correctly when arrays are the same size. + + ; RUN: echo "%X = constant [1x int] [int 8]" | llvm-as > %t.2.bc + ; RUN: llvm-as < %s > %t.1.bc + ; RUN: llvm-link %t.[12].bc | llvm-dis | grep constant + + %X = uninitialized global [1 x int] Index: llvm/test/Regression/Linker/ConstantGlobals2.ll diff -c /dev/null llvm/test/Regression/Linker/ConstantGlobals2.ll:1.1 *** /dev/null Mon Oct 4 21:12:33 2004 --- llvm/test/Regression/Linker/ConstantGlobals2.ll Mon Oct 4 21:12:20 2004 *************** *** 0 **** --- 1,7 ---- + ; Test that appending linkage works correctly when arrays are the same size. + + ; RUN: echo "%X = uninitialized global [1x int]" | llvm-as > %t.2.bc + ; RUN: llvm-as < %s > %t.1.bc + ; RUN: llvm-link %t.[12].bc | llvm-dis | grep constant + + %X = constant [1 x int] [ int 12 ] From lattner at cs.uiuc.edu Mon Oct 4 21:16:12 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 21:16:12 -0500 Subject: [llvm-commits] CVS: llvm/test/Regression/Linker/ConstantGlobals3.ll Message-ID: <200410050216.VAA22435@apoc.cs.uiuc.edu> Changes in directory llvm/test/Regression/Linker: ConstantGlobals3.ll added (r1.1) --- Log message: Another testcase for constness linkage --- Diffs of the changes: (+7 -0) Index: llvm/test/Regression/Linker/ConstantGlobals3.ll diff -c /dev/null llvm/test/Regression/Linker/ConstantGlobals3.ll:1.1 *** /dev/null Mon Oct 4 21:16:11 2004 --- llvm/test/Regression/Linker/ConstantGlobals3.ll Mon Oct 4 21:16:01 2004 *************** *** 0 **** --- 1,7 ---- + ; Test that appending linkage works correctly when arrays are the same size. + + ; RUN: echo "%X = uninitialized constant [1x int]" | llvm-as > %t.2.bc + ; RUN: llvm-as < %s > %t.1.bc + ; RUN: llvm-link %t.[12].bc | llvm-dis | grep constant + + %X = uninitialized global [1 x int] From lattner at cs.uiuc.edu Mon Oct 4 21:28:22 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 21:28:22 -0500 Subject: [llvm-commits] CVS: llvm/lib/VMCore/Linker.cpp Message-ID: <200410050228.VAA22927@apoc.cs.uiuc.edu> Changes in directory llvm/lib/VMCore: Linker.cpp updated: 1.85 -> 1.86 --- Log message: Make sure the const bit gets inherited correctly when linking declarations of disagreeing constness. This fixes test/Regression/Linker/ConstantGlobals[123].ll --- Diffs of the changes: (+15 -1) Index: llvm/lib/VMCore/Linker.cpp diff -u llvm/lib/VMCore/Linker.cpp:1.85 llvm/lib/VMCore/Linker.cpp:1.86 --- llvm/lib/VMCore/Linker.cpp:1.85 Fri Sep 10 23:25:17 2004 +++ llvm/lib/VMCore/Linker.cpp Mon Oct 4 21:28:11 2004 @@ -457,15 +457,26 @@ // external globals, we aren't adding anything. ValueMap.insert(std::make_pair(SGV, DGV)); + // Inherit 'const' information. + if (SGV->isConstant()) DGV->setConstant(true); + } else if (DGV->isExternal()) { // If DGV is external but SGV is not... ValueMap.insert(std::make_pair(SGV, DGV)); DGV->setLinkage(SGV->getLinkage()); // Inherit linkage! + + if (DGV->isConstant() && !SGV->isConstant()) + return Error(Err, "Linking globals named '" + SGV->getName() + + "': declaration is const but definition is not!"); + + // Inherit 'const' information. + if (SGV->isConstant()) DGV->setConstant(true); + } else if (SGV->hasWeakLinkage() || SGV->hasLinkOnceLinkage()) { // At this point we know that DGV has LinkOnce, Appending, Weak, or // External linkage. If DGV is Appending, this is an error. if (DGV->hasAppendingLinkage()) return Error(Err, "Linking globals named '" + SGV->getName() + - " ' with 'weak' and 'appending' linkage is not allowed!"); + "' with 'weak' and 'appending' linkage is not allowed!"); if (SGV->isConstant() != DGV->isConstant()) return Error(Err, "Global Variable Collision on '" + @@ -498,6 +509,9 @@ } else if (SGV->getLinkage() != DGV->getLinkage()) { return Error(Err, "Global variables named '" + SGV->getName() + "' have different linkage specifiers!"); + // Inherit 'const' information. + if (SGV->isConstant()) DGV->setConstant(true); + } else if (SGV->hasExternalLinkage()) { // Allow linking two exactly identical external global variables... if (SGV->isConstant() != DGV->isConstant()) From lattner at cs.uiuc.edu Mon Oct 4 21:30:00 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 21:30:00 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/garage/Makefile Message-ID: <200410050230.VAA25999@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/garage: Makefile added (r1.1) --- Log message: Wow, the first bm to work without modification! --- Diffs of the changes: (+6 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/garage/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/garage/Makefile:1.1 *** /dev/null Mon Oct 4 21:29:58 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/garage/Makefile Mon Oct 4 21:29:48 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = garage + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + From lattner at cs.uiuc.edu Mon Oct 4 21:35:16 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 21:35:16 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed/README dosgreed.cpp dosgreed.hpp greed.hpp Message-ID: <200410050235.VAA02034@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/greed: README (r1.1) removed dosgreed.cpp (r1.1) removed dosgreed.hpp (r1.1) removed greed.hpp (r1.1) removed --- Log message: This appears to be one of the benchmarks that has no hope of working. Nuke it --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Mon Oct 4 21:44:18 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 21:44:18 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/Makefile life.cpp Message-ID: <200410050244.VAA04457@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/life: Makefile added (r1.1) life.cpp updated: 1.1 -> 1.2 --- Log message: MAke this benchmakr build, work and take a reasonable amount of time --- Diffs of the changes: (+11 -6) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/Makefile:1.1 *** /dev/null Mon Oct 4 21:44:15 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/Makefile Mon Oct 4 21:44:05 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = life + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/life.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/life.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/life.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/life.cpp:1.1 Mon Oct 4 15:01:14 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/life/life.cpp Mon Oct 4 21:44:05 2004 @@ -4,7 +4,7 @@ const int N=40, STATES=4; // size of square board const int DRAB=3; const int DFOX=8; -const int CYCLES=10; +const int CYCLES=10000; enum state { EMPTY, GRASS, RABBIT, FOX }; class living; // forward decl @@ -141,8 +141,8 @@ { int i,j; - for (i = 1; i < N; ++i) - for (j = 1; j < N; ++j) + for (i = 1; i < N-1; ++i) + for (j = 1; j < N-1; ++j) delete (w[i][j]); } @@ -150,8 +150,8 @@ { int i,j; - for (i = 1; i < N; ++i) - for (j = 1; j < N; ++j) { + for (i = 0; i < N; ++i) + for (j = 0; j < N; ++j) { if (i == j) w[i][j] = new fox(i,j); else if (i < j) w[i][j] = new rabbit(i,j); else w[i][j] = new grass(i,j); @@ -164,7 +164,6 @@ int i; init(odd); - init(even); eden(even); From lattner at cs.uiuc.edu Mon Oct 4 21:58:09 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 21:58:09 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/Makefile objects.cpp onlyobj.h Message-ID: <200410050258.VAA05237@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects: Makefile added (r1.1) objects.cpp updated: 1.1 -> 1.2 onlyobj.h updated: 1.1 -> 1.2 --- Log message: Compile --- Diffs of the changes: (+13 -14) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/Makefile:1.1 *** /dev/null Mon Oct 4 21:58:08 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/Makefile Mon Oct 4 21:57:58 2004 *************** *** 0 **** --- 1,7 ---- + LEVEL = ../../../.. + + PROG = objects + LIBS = -lstdc++ + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/objects.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/objects.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/objects.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/objects.cpp:1.1 Mon Oct 4 15:01:14 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/objects.cpp Mon Oct 4 21:57:58 2004 @@ -4,11 +4,11 @@ // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #include "onlyobj.h" -int strlen(char *str1) {return 0;} -int strcmp(char *str1, char *str2) {return 0;} -char *strcpy(char *str1, char *str2) {return "";} -char *strncpy(char *str1, char *str2, int i) {return "";} -char *strcat(char *str1, char *str2) {return "";} +static int strlen(char *str1) {return 0;} +static int strcmp(char *str1, char *str2) {return 0;} +static char *strcpy(char *str1, char *str2) {return "";} +static char *strncpy(char *str1, char *str2, int i) {return "";} +static char *strcat(char *str1, char *str2) {return "";} #include "artest.h" @@ -261,7 +261,7 @@ }; -main () +int main () { A *a1 = new A(1); A *a2 = new A(2); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/onlyobj.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/onlyobj.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/onlyobj.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/onlyobj.h:1.1 Mon Oct 4 15:01:14 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/objects/onlyobj.h Mon Oct 4 21:57:58 2004 @@ -5,14 +5,6 @@ #ifndef __OBJ__ -extern "C" { -int strlen(char *str1); -int strcmp(char *str1, char *str2); -char *strcpy(char *str1, char *str2); -char *strncpy(char *str1, char *str2, int i); -char *strcat(char *str1, char *str2); -} - class Object { public : From lattner at cs.uiuc.edu Mon Oct 4 22:35:31 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 22:35:31 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/Makefile cell.hh constants.hh coordinate.hh obstacle.hh ocean.cpp ocean.hh predator.hh prey.hh Message-ID: <200410050335.WAA06412@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean: Makefile added (r1.1) cell.hh updated: 1.1 -> 1.2 constants.hh updated: 1.1 -> 1.2 coordinate.hh updated: 1.1 -> 1.2 obstacle.hh updated: 1.1 -> 1.2 ocean.cpp updated: 1.1 -> 1.2 ocean.hh updated: 1.1 -> 1.2 predator.hh updated: 1.1 -> 1.2 prey.hh updated: 1.1 -> 1.2 --- Log message: Make this thing work, implement critical methods that are needed to avoid going into an infinite loop, etc. --- Diffs of the changes: (+23 -21) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/Makefile:1.1 *** /dev/null Mon Oct 4 22:35:26 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/Makefile Mon Oct 4 22:35:13 2004 *************** *** 0 **** --- 1,7 ---- + LEVEL = ../../../.. + + PROG = ocean + #LIBS = -lstdc++ + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/cell.hh diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/cell.hh:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/cell.hh:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/cell.hh:1.1 Mon Oct 4 15:01:14 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/cell.hh Mon Oct 4 22:35:13 2004 @@ -20,7 +20,7 @@ virtual Cell *reproduce(Coordinate anOffset); public: - Cell(Coordinate &aCoord) { + Cell(const Coordinate &aCoord) { offset = new Coordinate(aCoord); image = DefaultImage; } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/constants.hh diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/constants.hh:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/constants.hh:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/constants.hh:1.1 Mon Oct 4 15:01:14 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/constants.hh Mon Oct 4 22:35:13 2004 @@ -1,12 +1,12 @@ #ifndef Constants #define Constants -#define MaxRows 25 -#define MaxCols 70 +#define MaxRows 2500 +#define MaxCols 5000 -#define DefaultNumObstacles 75 -#define DefaultNumPredators 20 -#define DefaultNumPrey 150 +#define DefaultNumObstacles 750 +#define DefaultNumPredators 200 +#define DefaultNumPrey 1000 #define DefaultNumIterations 1000 Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/coordinate.hh diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/coordinate.hh:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/coordinate.hh:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/coordinate.hh:1.1 Mon Oct 4 15:01:14 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/coordinate.hh Mon Oct 4 22:35:13 2004 @@ -8,7 +8,7 @@ public: Coordinate(unsigned anX, unsigned aY) : x(anX), y(aY) {} - Coordinate(Coordinate &aCoord) { + Coordinate(const Coordinate &aCoord) { x = aCoord.x; y = aCoord.y; } @@ -18,14 +18,14 @@ unsigned getY(void) {return y;} void setX(unsigned anX) {x = anX;} void setY(unsigned aY) {y = aY;} - void operator = (Coordinate &aCoord) { + void operator = (const Coordinate &aCoord) { x = aCoord.x; y = aCoord.y; } - int operator == (Coordinate &c) { + int operator == (const Coordinate &c) { return (x == c.x && y == c.y); } - int operator != (Coordinate &c) { + int operator != (const Coordinate &c) { return (x != c.x && y != c.y); } }; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/obstacle.hh diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/obstacle.hh:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/obstacle.hh:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/obstacle.hh:1.1 Mon Oct 4 15:01:14 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/obstacle.hh Mon Oct 4 22:35:13 2004 @@ -6,7 +6,6 @@ Obstacle(Coordinate &aCoord) : Cell(aCoord) { image = ObstacleImage; } - virtual ~Obstacle(void) {Cell::~Cell();} }; #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.cpp:1.1 Mon Oct 4 15:01:14 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.cpp Mon Oct 4 22:35:13 2004 @@ -7,6 +7,8 @@ #include "predator.hh" #include "obstacle.hh" +#include + //cell.cc Cell *Cell::getCellAt(Coordinate aCoord) { return cells[aCoord.getY()][aCoord.getX()]; @@ -121,11 +123,11 @@ #define MAX 32767 float Random::randReal(void) { - return 0.0; + return random()/(float)RAND_MAX; } unsigned Random::nextIntBetween(int low, int high) { - return 0; + return (long long)(random())* high / RAND_MAX; } //ocean.cc @@ -144,10 +146,6 @@ void Ocean::initCells(void) { addEmptyCells(); - if (numPredators == (size - numObstacles)) - numPredators = size - numObstacles; - if (numPrey == (size - numObstacles - numPredators)) - numPrey = size - numObstacles - numPredators; addObstacles(); addPredators(); addPrey(); @@ -229,7 +227,7 @@ } } -main() { +int main() { Ocean *myOcean = new Ocean; myOcean->initialize(); myOcean->run(); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.hh diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.hh:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.hh:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.hh:1.1 Mon Oct 4 15:01:14 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/ocean.hh Mon Oct 4 22:35:13 2004 @@ -9,7 +9,6 @@ private: unsigned numRows; unsigned numCols; - unsigned size; unsigned numPrey; unsigned numPredators; unsigned numObstacles; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/predator.hh diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/predator.hh:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/predator.hh:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/predator.hh:1.1 Mon Oct 4 15:01:14 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/predator.hh Mon Oct 4 22:35:13 2004 @@ -13,7 +13,6 @@ timeToFeed = TimeToFeed; image = DefaultPredImage; } - virtual ~Predator(void) {Prey::~Prey();} virtual void process(void); }; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/prey.hh diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/prey.hh:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/prey.hh:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/prey.hh:1.1 Mon Oct 4 15:01:14 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/ocean/prey.hh Mon Oct 4 22:35:13 2004 @@ -13,7 +13,7 @@ timeToReproduce = TimeToReproduce; image = DefaultPreyImage; } - ~Prey(void) {Cell::~Cell();} + void process(void) { Coordinate toCoord; From lattner at cs.uiuc.edu Mon Oct 4 22:39:01 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 22:39:01 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/Makefile office.cpp Message-ID: <200410050339.WAA06595@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/office: Makefile added (r1.1) office.cpp updated: 1.1 -> 1.2 --- Log message: Make this work --- Diffs of the changes: (+10 -2) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/Makefile:1.1 *** /dev/null Mon Oct 4 22:38:58 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/Makefile Mon Oct 4 22:38:47 2004 *************** *** 0 **** --- 1,7 ---- + LEVEL = ../../../.. + + PROG = office + #LIBS = -lstdc++ + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/office.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/office.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/office.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/office.cpp:1.1 Mon Oct 4 15:01:14 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/office/office.cpp Mon Oct 4 22:38:47 2004 @@ -1,6 +1,7 @@ // Chapter 11 - Program 4 -#include +#include #include "supervsr.h" +using namespace std; // In all cases, init_data assigns values to the class variables and // display outputs the values to the monitor for inspection. @@ -101,7 +102,7 @@ person *staff1,*staff2,*staff3,*staff4; -main() +int main() { supervisor *suppt; programmer *progpt; From lattner at cs.uiuc.edu Mon Oct 4 22:40:50 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 22:40:50 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/Makefile primes.cpp Message-ID: <200410050340.WAA06943@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes: Makefile added (r1.1) primes.cpp updated: 1.1 -> 1.2 --- Log message: Make this compile and take a nontrivial amount of time --- Diffs of the changes: (+10 -2) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/Makefile:1.1 *** /dev/null Mon Oct 4 22:40:49 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/Makefile Mon Oct 4 22:40:39 2004 *************** *** 0 **** --- 1,7 ---- + LEVEL = ../../../.. + + PROG = primes + #LIBS = -lstdc++ + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/primes.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/primes.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/primes.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/primes.cpp:1.1 Mon Oct 4 15:01:15 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/primes/primes.cpp Mon Oct 4 22:40:39 2004 @@ -24,14 +24,15 @@ int out(); filter(item *src, int f) : item (src) {factor = f;} }; -main() { + +int main() { counter c(2); sieve s(&c); int next; do { next = s.out(); printf("%d ",next); - } while (next < 61); + } while (next < 100001); printf ("\n"); } int sieve::out() { From lattner at cs.uiuc.edu Mon Oct 4 22:42:27 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 22:42:27 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/Makefile bjarne.cpp Message-ID: <200410050342.WAA07064@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes: Makefile added (r1.1) bjarne.cpp updated: 1.1 -> 1.2 --- Log message: Make this compile --- Diffs of the changes: (+9 -1) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/Makefile:1.1 *** /dev/null Mon Oct 4 22:42:26 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/Makefile Mon Oct 4 22:42:16 2004 *************** *** 0 **** --- 1,7 ---- + LEVEL = ../../../.. + + PROG = shapes + #LIBS = -lstdc++ + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/bjarne.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/bjarne.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/bjarne.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/bjarne.cpp:1.1 Mon Oct 4 15:01:15 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/shapes/bjarne.cpp Mon Oct 4 22:42:16 2004 @@ -1,7 +1,8 @@ /* this program is taken from Section 6.4 in Bjarne Stroustrup's book "The C++ Programming Language" 2nd Edition. */ -#include +#include #include "bjarne.h" +using namespace std; enum color {black='*', white=' '}; From lattner at cs.uiuc.edu Mon Oct 4 22:46:00 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 22:46:00 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/Makefile simulate.cpp Message-ID: <200410050346.WAA07328@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul: Makefile added (r1.1) simulate.cpp updated: 1.1 -> 1.2 --- Log message: Remove infinite loop --- Diffs of the changes: (+9 -2) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/Makefile:1.1 *** /dev/null Mon Oct 4 22:45:59 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/Makefile Mon Oct 4 22:45:49 2004 *************** *** 0 **** --- 1,7 ---- + LEVEL = ../../../.. + + PROG = simul + #LIBS = -lstdc++ + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/simulate.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/simulate.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/simulate.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/simulate.cpp:1.1 Mon Oct 4 15:01:15 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/simul/simulate.cpp Mon Oct 4 22:45:49 2004 @@ -248,7 +248,7 @@ } }; -main() { +int main() { screen.clear_screen(); int pop_factor = 1; int crawl_factor = 2; @@ -263,7 +263,7 @@ } int xrand = 5; int yrand = 6; - while (1) { + for (int i = 0; i != 1000000; ++i) { int x_location = xrand; int y_location = yrand; if (s_grid[x_location][y_location]) From lattner at cs.uiuc.edu Mon Oct 4 22:50:58 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 22:50:58 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/Makefile tree.cpp tree.h Message-ID: <200410050350.WAA07677@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees: Makefile added (r1.1) tree.cpp updated: 1.1 -> 1.2 tree.h updated: 1.1 -> 1.2 --- Log message: Make this compile and work --- Diffs of the changes: (+12 -5) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/Makefile:1.1 *** /dev/null Mon Oct 4 22:50:57 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/Makefile Mon Oct 4 22:50:47 2004 *************** *** 0 **** --- 1,7 ---- + LEVEL = ../../../.. + + PROG = trees + LIBS = -lstdc++ + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.cpp:1.1 Mon Oct 4 15:01:15 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.cpp Mon Oct 4 22:50:47 2004 @@ -86,7 +86,7 @@ // RealNode.cc -RealNode::RealNode(float k, char* ch) { +RealNode::RealNode(float k, char* ch) : symbol(0) { n = k; if (ch) { strlen(ch), symbol = new char; @@ -107,7 +107,7 @@ // main.cc -main () { +int main () { Tree t1(1), t2("u"), t3(5); Tree t4(t1,"*",t2); Tree t5("-",t3); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.h diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.h:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.h:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.h:1.1 Mon Oct 4 15:01:15 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/trees/tree.h Mon Oct 4 22:50:47 2004 @@ -50,7 +50,7 @@ RealNode(float k, char* ch=0); - ~RealNode(void) {delete symbol; this->Node::~Node();} + ~RealNode(void) {delete symbol; } float nodeValue(); }; @@ -66,7 +66,7 @@ UnaryNode(char* a, Tree b); - ~UnaryNode(void) {delete op; delete opnd; this->Node::~Node();} + ~UnaryNode(void) {delete op; delete opnd; } float nodeValue(); }; @@ -84,7 +84,7 @@ BinaryNode(char* a, Tree b, Tree c); - ~BinaryNode(void) {delete op; delete left; delete right; this->Node::~Node();} + ~BinaryNode(void) {delete op; delete left; delete right; } float nodeValue(); }; From lattner at cs.uiuc.edu Mon Oct 4 22:51:41 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 22:51:41 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/Makefile vcirc.cpp Message-ID: <200410050351.WAA07919@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc: Makefile added (r1.1) vcirc.cpp updated: 1.1 -> 1.2 --- Log message: Wow, this one just worked! --- Diffs of the changes: (+8 -1) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/Makefile:1.1 *** /dev/null Mon Oct 4 22:51:40 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/Makefile Mon Oct 4 22:51:30 2004 *************** *** 0 **** --- 1,7 ---- + LEVEL = ../../../.. + + PROG = vcirc + #LIBS = -lstdc++ + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/vcirc.cpp diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/vcirc.cpp:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/vcirc.cpp:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/vcirc.cpp:1.1 Mon Oct 4 15:01:15 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/vcirc/vcirc.cpp Mon Oct 4 22:51:30 2004 @@ -93,7 +93,7 @@ Expand(-ContractBy); // redraws with (Radius - ContractBy) } -main() // test the functions +int main() // test the functions { Circle MyCircle(50, 100, 25); // declare a circle object MyCircle.Show(); // show it From lattner at cs.uiuc.edu Mon Oct 4 22:53:09 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 22:53:09 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/Makefile Message-ID: <200410050353.WAA08454@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm: Makefile added (r1.1) --- Log message: Dont' forget this --- Diffs of the changes: (+6 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/Makefile:1.1 *** /dev/null Mon Oct 4 22:53:08 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/fsm/Makefile Mon Oct 4 22:52:58 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = fsm + LDFLAGS = -lstdc++ + include $(LEVEL)/MultiSource/Makefile.multisrc + From lattner at cs.uiuc.edu Mon Oct 4 22:53:21 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 22:53:21 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/Makefile Message-ID: <200410050353.WAA08462@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP: Makefile updated: 1.1 -> 1.2 --- Log message: cleanup --- Diffs of the changes: (+0 -6) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/Makefile diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/Makefile:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/Makefile:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/Makefile:1.1 Mon Oct 4 15:07:40 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C++/NP/Makefile Mon Oct 4 22:53:10 2004 @@ -1,12 +1,6 @@ LEVEL = ../../../.. PROG = np -#CPPFLAGS = -DVERSION='"1.00"' -DCOMPDATE="\"today\"" -DCFLAGS='""' -DHOSTNAME="\"thishost\"" LDFLAGS = -lstdc++ -ifdef LARGE_PROBLEM_SIZE -#RUN_OPTIONS = ref.in -else -#RUN_OPTIONS = test.in -endif include $(LEVEL)/MultiSource/Makefile.multisrc From lattner at cs.uiuc.edu Mon Oct 4 22:54:35 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 22:54:35 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C++/Makefile Message-ID: <200410050354.WAA08552@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C++: Makefile added (r1.1) --- Log message: These are the ones that survived --- Diffs of the changes: (+4 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C++/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C++/Makefile:1.1 *** /dev/null Mon Oct 4 22:54:34 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C++/Makefile Mon Oct 4 22:54:24 2004 *************** *** 0 **** --- 1,4 ---- + LEVEL = ../../.. + PARALLEL_DIRS := NP city deriv1 deriv2 employ family fsm garage \ + life objects ocean office primes shapes simul trees vcirc + include $(LEVEL)/Makefile.programs From lattner at cs.uiuc.edu Mon Oct 4 22:54:53 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 4 Oct 2004 22:54:53 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Makefile Message-ID: <200410050354.WAA08556@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks: Makefile updated: 1.5 -> 1.6 --- Log message: Add Prolangs-C++ suite --- Diffs of the changes: (+2 -3) Index: llvm-test/MultiSource/Benchmarks/Makefile diff -u llvm-test/MultiSource/Benchmarks/Makefile:1.5 llvm-test/MultiSource/Benchmarks/Makefile:1.6 --- llvm-test/MultiSource/Benchmarks/Makefile:1.5 Wed Sep 1 09:33:21 2004 +++ llvm-test/MultiSource/Benchmarks/Makefile Mon Oct 4 22:54:12 2004 @@ -1,8 +1,7 @@ # MultiSource/Benchmarks Makefile: Build all subdirectories automatically LEVEL = ../.. - -PARALLEL_DIRS := Fhourstones McCat Olden OptimizerEval Ptrdist llubenchmark sim FreeBench MallocBench - +PARALLEL_DIRS := Fhourstones McCat Olden OptimizerEval Ptrdist llubenchmark \ + sim FreeBench MallocBench Prolangs-C++ include $(LEVEL)/Makefile.programs From gaeke at cs.uiuc.edu Tue Oct 5 10:44:03 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Tue, 5 Oct 2004 10:44:03 -0500 Subject: [llvm-commits] CVS: reopt/test/run-tests Message-ID: <200410051544.KAA26154@zion.cs.uiuc.edu> Changes in directory reopt/test: run-tests updated: 1.22 -> 1.23 --- Log message: Fix bug in -list option --- Diffs of the changes: (+1 -1) Index: reopt/test/run-tests diff -u reopt/test/run-tests:1.22 reopt/test/run-tests:1.23 --- reopt/test/run-tests:1.22 Mon Oct 4 15:15:29 2004 +++ reopt/test/run-tests Tue Oct 5 10:43:51 2004 @@ -44,7 +44,7 @@ echo "" echo "SUPPORTED TESTS:" echo "----------------" - grep SUBDIR= $0 | egrep -v '(exec|grep|ucname)' | sed 's/) / /' | sed 's/;.*$//' + grep SUBDIR= $0 | egrep -v '(EXTRA|exec|grep|ucname)' | sed 's/) / /' | sed 's/;.*$//' if [ -d $EXTRATESTDIR ]; then for d in ${EXTRATESTDIR}/*; do arg=`basename $d | tr A-Z a-z` From gaeke at cs.uiuc.edu Tue Oct 5 10:49:07 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Tue, 5 Oct 2004 10:49:07 -0500 Subject: [llvm-commits] CVS: reopt/lib/LightWtProfiling/RuntimeOptimizations.cpp Message-ID: <200410051549.KAA26267@zion.cs.uiuc.edu> Changes in directory reopt/lib/LightWtProfiling: RuntimeOptimizations.cpp updated: 1.52 -> 1.53 --- Log message: Only print gdb commands relating to the optimized trace, not the SLI trace, after trace emission. --- Diffs of the changes: (+0 -2) Index: reopt/lib/LightWtProfiling/RuntimeOptimizations.cpp diff -u reopt/lib/LightWtProfiling/RuntimeOptimizations.cpp:1.52 reopt/lib/LightWtProfiling/RuntimeOptimizations.cpp:1.53 --- reopt/lib/LightWtProfiling/RuntimeOptimizations.cpp:1.52 Mon Oct 4 16:18:25 2004 +++ reopt/lib/LightWtProfiling/RuntimeOptimizations.cpp Tue Oct 5 10:48:57 2004 @@ -35,8 +35,6 @@ uint64_t traceEndAddr) { DEBUG (std::cerr << "\n*** About to return from optimizeTrace() for trace #" << TraceCount << ". GDB commands:\n" << std::hex - << "display/i $pc\n" - << "b *0x" << a << "\n" << "b *0x" << traceStartAddr << "\n" << "disassemble 0x" << traceStartAddr << " 0x" << traceEndAddr << "\n" << std::dec); From lattner at cs.uiuc.edu Tue Oct 5 11:55:21 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 11:55:21 -0500 Subject: [llvm-commits] CVS: llvm-test/SingleSource/Benchmarks/Misc/bigfib.cpp Message-ID: <200410051655.LAA19021@apoc.cs.uiuc.edu> Changes in directory llvm-test/SingleSource/Benchmarks/Misc: bigfib.cpp added (r1.1) --- Log message: new testcase --- Diffs of the changes: (+311 -0) Index: llvm-test/SingleSource/Benchmarks/Misc/bigfib.cpp diff -c /dev/null llvm-test/SingleSource/Benchmarks/Misc/bigfib.cpp:1.1 *** /dev/null Tue Oct 5 11:55:17 2004 --- llvm-test/SingleSource/Benchmarks/Misc/bigfib.cpp Tue Oct 5 11:55:07 2004 *************** *** 0 **** --- 1,311 ---- + // ########################################### + // [C++] Computing very long Fibonacci numbers + // Version 2.5.1 (with performance test) + // ------------------------------------------- + // Created by Alex Vinokur + // http://up.to/alexvn + // ########################################### + + // http://groups.google.com/groups?selm=bo4nls%2417vfq6%241%40ID-79865.news.uni-berlin.de + + #include + #include + #include + #include + #include + #include + #include + #include + using namespace std; + + + #define MAX_VALUE(x,y) ((x) > (y) ? (x) : (y)) + #define ASSERT(x) + // #define ASSERT(x) assert(x) + + + #define MAX_UNIT_VALUE (ULONG_MAX >> 2) + #define BASE1 10 + #define BASE2 1000000000 // BASE1 ** (BASE1 - 1) + + #if (BASE2 >= MAX_UNIT_VALUE) + #error Compilation Error-1 : (BASE2 >= MAX_UNIT_VALUE) + #endif + + #if (!(BASE1 * (BASE2/BASE1 + 1) < MAX_UNIT_VALUE)) + #error Compilation Error-2 : (!(BASE1 * (BASE2/BASE1 + 1) < MAX_UNIT_VALUE)) + #endif + + + typedef unsigned int uint; + typedef unsigned long ulong; + + // ========= + class BigInt + // ========= + { + friend ostream& operator<< (ostream& os, const BigInt& ins_i); + + private : + static ulong head_s; + vector units_; + + public : + BigInt (ulong unit_i) + { + ASSERT (unit_i < BASE2); + units_.push_back (unit_i); + } + + BigInt (BigInt big1_i, BigInt big2_i) + { + const ulong max_size = MAX_VALUE (big1_i.units_.size (), big2_i.units_.size ()); + + big1_i.units_.resize(max_size); + big2_i.units_.resize(max_size); + units_.resize(max_size); + + head_s = 0; + transform (big1_i.units_.begin(), big1_i.units_.end(), big2_i.units_.begin(), units_.begin(), *this); + + if (head_s) units_.push_back (head_s); + + } + + ulong operator() (const ulong n1, const ulong n2) + { + const ulong value = n1 + n2 + head_s; + head_s = value/BASE2; + return (value%BASE2); + } + }; + + + // -------------- + inline ostream& operator<< (ostream& os, const BigInt& ins_i) + { + ASSERT (!ins_i.units_.empty ()); + for (ulong i = (ins_i.units_.size () - 1); i; --i) + { + os << ins_i.units_ [i] << setw (BASE1 - 1) << setfill ('0'); + } return os << ins_i.units_ [0]; + } + + + // ============ + class Fibonacci + // ============ + { + private : + vector fibs_; + BigInt get_number (uint n_i = 0); + + public : + void show_all_numbers () const; + void show_last_number () const; + void show_number (ulong n_i); + + Fibonacci (uint n_i = 0) { get_number (n_i); } + ~Fibonacci () {} + + }; + + + // ----------------------- + BigInt Fibonacci::get_number (uint n_i) + { + fibs_.reserve(n_i + 1); + const uint cur_size = fibs_.size (); + + for (uint i = cur_size; i <= n_i; ++i) + { + switch (i) + { + case 0 : + fibs_.push_back (BigInt(0)); + break; + + case 1 : + if (fibs_.empty ()) fibs_.push_back (BigInt (0)); + fibs_.push_back(BigInt (1)); + break; + + default : + fibs_.push_back (BigInt (get_number (i - 2), get_number (i - 1))); + break; + } + } + + ASSERT (n_i < fibs_.size()); + return fibs_ [n_i]; + + } + + + // ----------------------- + void Fibonacci::show_all_numbers () const + { + ostringstream oss; + + for (uint i = 0; i < fibs_.size (); ++i) + { + oss << "Fib [" << i << "] = " << fibs_ [i] << "\n"; + } cout << oss.str(); + } + + + // ----------------------- + void Fibonacci::show_last_number () const + { + ostringstream oss; + + oss << "Fib [" << (fibs_.size() - 1) << "] = " << fibs_.back() << "\n"; + + cout << oss.str(); + } + + + + // ----------------------- + void Fibonacci::show_number (ulong n_i) + { + ostringstream oss; + + if (!(n_i < fibs_.size())) get_number (n_i); + + oss << "Fib [" << n_i << "] = " << fibs_[n_i] << "\n"; + + cout << oss.str(); + } + + // ------------------- + ulong BigInt::head_s (0); + + + + + // ============================== + #define ALL_FIBS "all" + #define TH_FIB "th" + #define SOME_FIBS "some" + #define RAND_FIBS "rand" + + #define MAX_RAND_FIB 25000 + + #define SETW1 4 + + // --------------------- + void usage (char **argv) + { + argv[0] = "bigfib"; + cerr << "USAGE : " + << endl + + << " " + << argv[0] + << " " + << setw (SETW1) + << std::left + << ALL_FIBS + << " ---> Fibonacci [0 - N]" + << endl + + << " " + << argv[0] + << " " + << std::left + << setw (SETW1) + << TH_FIB + << " ---> Fibonacci [N]" + << endl + + << " " + << argv[0] + << " " + << std::left + << setw (SETW1) + << SOME_FIBS + << " [ ...] ---> Fibonacci [N1], Fibonacci [N2], ..." + << endl + + << " " + << argv[0] + << " " + << std::left + << setw (SETW1) + << RAND_FIBS + << " [] ---> K random Fibonacci numbers ( < M; Default = " + << MAX_RAND_FIB + << " )" + << endl; + } + + + // --------------------- + string check (int argc, char **argv) + { + if (argc < 3) return string(); + + const string str (argv[1]); + if ( + (str == ALL_FIBS) + || + (str == TH_FIB) + || + (str == SOME_FIBS) + || + (str == RAND_FIBS) + ) + { + return str; + } + return string(); + + } + + + // --------------------- + + int main (int argc, char **argv) + { + string option (check (argc, argv)); + uint N; + if (option.empty()) { + // usage (argv); + // return 1; + option = TH_FIB; + N = 50000; + } else { + N = atoi (argv[2]); + } + + if (option == ALL_FIBS) + { + Fibonacci fib(N); + fib.show_all_numbers(); + } + + if (option == TH_FIB) + { + Fibonacci fib(N); + fib.show_last_number(); + } + + if (option == SOME_FIBS) + { + Fibonacci fib; + for (int i = 2; i < argc; i++) fib.show_number (atoi(argv[i])); + } + + if (option == RAND_FIBS) + { + const int max_rand_fib = (argc == 3) ? MAX_RAND_FIB : atoi (argv[3]); + Fibonacci fib; + for (uint i = 0; i < N; i++) fib.show_number (rand()%max_rand_fib); + } + + return 0; + } + + + From lattner at cs.uiuc.edu Tue Oct 5 11:57:32 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 11:57:32 -0500 Subject: [llvm-commits] CVS: llvm-test/SingleSource/Benchmarks/Misc/Makefile Message-ID: <200410051657.LAA19075@apoc.cs.uiuc.edu> Changes in directory llvm-test/SingleSource/Benchmarks/Misc: Makefile updated: 1.3 -> 1.4 --- Log message: add libstdc++ --- Diffs of the changes: (+2 -1) Index: llvm-test/SingleSource/Benchmarks/Misc/Makefile diff -u llvm-test/SingleSource/Benchmarks/Misc/Makefile:1.3 llvm-test/SingleSource/Benchmarks/Misc/Makefile:1.4 --- llvm-test/SingleSource/Benchmarks/Misc/Makefile:1.3 Wed Sep 1 09:33:26 2004 +++ llvm-test/SingleSource/Benchmarks/Misc/Makefile Tue Oct 5 11:57:21 2004 @@ -1,5 +1,6 @@ LEVEL = ../../.. -LDFLAGS += -lm +LDFLAGS += -lm -lstdc++ +LIBS = -lstdc++ FP_TOLERANCE := 0.001 include $(LEVEL)/SingleSource/Makefile.singlesrc From lattner at cs.uiuc.edu Tue Oct 5 11:58:48 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 11:58:48 -0500 Subject: [llvm-commits] CVS: llvm-test/SingleSource/Benchmarks/Misc-C++/ Message-ID: <200410051658.LAA19222@apoc.cs.uiuc.edu> Changes in directory llvm-test/SingleSource/Benchmarks/Misc-C++: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/SingleSource/Benchmarks/Misc-C++ added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 11:58:57 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 11:58:57 -0500 Subject: [llvm-commits] CVS: llvm-test/SingleSource/Benchmarks/Misc-C++/Makefile bigfib.cpp Message-ID: <200410051658.LAA19232@apoc.cs.uiuc.edu> Changes in directory llvm-test/SingleSource/Benchmarks/Misc-C++: Makefile added (r1.1) bigfib.cpp added (r1.1) --- Log message: Add new benchmark --- Diffs of the changes: (+316 -0) Index: llvm-test/SingleSource/Benchmarks/Misc-C++/Makefile diff -c /dev/null llvm-test/SingleSource/Benchmarks/Misc-C++/Makefile:1.1 *** /dev/null Tue Oct 5 11:58:56 2004 --- llvm-test/SingleSource/Benchmarks/Misc-C++/Makefile Tue Oct 5 11:58:46 2004 *************** *** 0 **** --- 1,5 ---- + LEVEL = ../../.. + LDFLAGS += -lm -lstdc++ + LIBS = -lstdc++ + + include $(LEVEL)/SingleSource/Makefile.singlesrc Index: llvm-test/SingleSource/Benchmarks/Misc-C++/bigfib.cpp diff -c /dev/null llvm-test/SingleSource/Benchmarks/Misc-C++/bigfib.cpp:1.1 *** /dev/null Tue Oct 5 11:58:57 2004 --- llvm-test/SingleSource/Benchmarks/Misc-C++/bigfib.cpp Tue Oct 5 11:58:46 2004 *************** *** 0 **** --- 1,311 ---- + // ########################################### + // [C++] Computing very long Fibonacci numbers + // Version 2.5.1 (with performance test) + // ------------------------------------------- + // Created by Alex Vinokur + // http://up.to/alexvn + // ########################################### + + // http://groups.google.com/groups?selm=bo4nls%2417vfq6%241%40ID-79865.news.uni-berlin.de + + #include + #include + #include + #include + #include + #include + #include + #include + using namespace std; + + + #define MAX_VALUE(x,y) ((x) > (y) ? (x) : (y)) + #define ASSERT(x) + // #define ASSERT(x) assert(x) + + + #define MAX_UNIT_VALUE (ULONG_MAX >> 2) + #define BASE1 10 + #define BASE2 1000000000 // BASE1 ** (BASE1 - 1) + + #if (BASE2 >= MAX_UNIT_VALUE) + #error Compilation Error-1 : (BASE2 >= MAX_UNIT_VALUE) + #endif + + #if (!(BASE1 * (BASE2/BASE1 + 1) < MAX_UNIT_VALUE)) + #error Compilation Error-2 : (!(BASE1 * (BASE2/BASE1 + 1) < MAX_UNIT_VALUE)) + #endif + + + typedef unsigned int uint; + typedef unsigned long ulong; + + // ========= + class BigInt + // ========= + { + friend ostream& operator<< (ostream& os, const BigInt& ins_i); + + private : + static ulong head_s; + vector units_; + + public : + BigInt (ulong unit_i) + { + ASSERT (unit_i < BASE2); + units_.push_back (unit_i); + } + + BigInt (BigInt big1_i, BigInt big2_i) + { + const ulong max_size = MAX_VALUE (big1_i.units_.size (), big2_i.units_.size ()); + + big1_i.units_.resize(max_size); + big2_i.units_.resize(max_size); + units_.resize(max_size); + + head_s = 0; + transform (big1_i.units_.begin(), big1_i.units_.end(), big2_i.units_.begin(), units_.begin(), *this); + + if (head_s) units_.push_back (head_s); + + } + + ulong operator() (const ulong n1, const ulong n2) + { + const ulong value = n1 + n2 + head_s; + head_s = value/BASE2; + return (value%BASE2); + } + }; + + + // -------------- + inline ostream& operator<< (ostream& os, const BigInt& ins_i) + { + ASSERT (!ins_i.units_.empty ()); + for (ulong i = (ins_i.units_.size () - 1); i; --i) + { + os << ins_i.units_ [i] << setw (BASE1 - 1) << setfill ('0'); + } return os << ins_i.units_ [0]; + } + + + // ============ + class Fibonacci + // ============ + { + private : + vector fibs_; + BigInt get_number (uint n_i = 0); + + public : + void show_all_numbers () const; + void show_last_number () const; + void show_number (ulong n_i); + + Fibonacci (uint n_i = 0) { get_number (n_i); } + ~Fibonacci () {} + + }; + + + // ----------------------- + BigInt Fibonacci::get_number (uint n_i) + { + fibs_.reserve(n_i + 1); + const uint cur_size = fibs_.size (); + + for (uint i = cur_size; i <= n_i; ++i) + { + switch (i) + { + case 0 : + fibs_.push_back (BigInt(0)); + break; + + case 1 : + if (fibs_.empty ()) fibs_.push_back (BigInt (0)); + fibs_.push_back(BigInt (1)); + break; + + default : + fibs_.push_back (BigInt (get_number (i - 2), get_number (i - 1))); + break; + } + } + + ASSERT (n_i < fibs_.size()); + return fibs_ [n_i]; + + } + + + // ----------------------- + void Fibonacci::show_all_numbers () const + { + ostringstream oss; + + for (uint i = 0; i < fibs_.size (); ++i) + { + oss << "Fib [" << i << "] = " << fibs_ [i] << "\n"; + } cout << oss.str(); + } + + + // ----------------------- + void Fibonacci::show_last_number () const + { + ostringstream oss; + + oss << "Fib [" << (fibs_.size() - 1) << "] = " << fibs_.back() << "\n"; + + cout << oss.str(); + } + + + + // ----------------------- + void Fibonacci::show_number (ulong n_i) + { + ostringstream oss; + + if (!(n_i < fibs_.size())) get_number (n_i); + + oss << "Fib [" << n_i << "] = " << fibs_[n_i] << "\n"; + + cout << oss.str(); + } + + // ------------------- + ulong BigInt::head_s (0); + + + + + // ============================== + #define ALL_FIBS "all" + #define TH_FIB "th" + #define SOME_FIBS "some" + #define RAND_FIBS "rand" + + #define MAX_RAND_FIB 25000 + + #define SETW1 4 + + // --------------------- + void usage (char **argv) + { + argv[0] = "bigfib"; + cerr << "USAGE : " + << endl + + << " " + << argv[0] + << " " + << setw (SETW1) + << std::left + << ALL_FIBS + << " ---> Fibonacci [0 - N]" + << endl + + << " " + << argv[0] + << " " + << std::left + << setw (SETW1) + << TH_FIB + << " ---> Fibonacci [N]" + << endl + + << " " + << argv[0] + << " " + << std::left + << setw (SETW1) + << SOME_FIBS + << " [ ...] ---> Fibonacci [N1], Fibonacci [N2], ..." + << endl + + << " " + << argv[0] + << " " + << std::left + << setw (SETW1) + << RAND_FIBS + << " [] ---> K random Fibonacci numbers ( < M; Default = " + << MAX_RAND_FIB + << " )" + << endl; + } + + + // --------------------- + string check (int argc, char **argv) + { + if (argc < 3) return string(); + + const string str (argv[1]); + if ( + (str == ALL_FIBS) + || + (str == TH_FIB) + || + (str == SOME_FIBS) + || + (str == RAND_FIBS) + ) + { + return str; + } + return string(); + + } + + + // --------------------- + + int main (int argc, char **argv) + { + string option (check (argc, argv)); + uint N; + if (option.empty()) { + // usage (argv); + // return 1; + option = TH_FIB; + N = 50000; + } else { + N = atoi (argv[2]); + } + + if (option == ALL_FIBS) + { + Fibonacci fib(N); + fib.show_all_numbers(); + } + + if (option == TH_FIB) + { + Fibonacci fib(N); + fib.show_last_number(); + } + + if (option == SOME_FIBS) + { + Fibonacci fib; + for (int i = 2; i < argc; i++) fib.show_number (atoi(argv[i])); + } + + if (option == RAND_FIBS) + { + const int max_rand_fib = (argc == 3) ? MAX_RAND_FIB : atoi (argv[3]); + Fibonacci fib; + for (uint i = 0; i < N; i++) fib.show_number (rand()%max_rand_fib); + } + + return 0; + } + + + From lattner at cs.uiuc.edu Tue Oct 5 11:59:20 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 11:59:20 -0500 Subject: [llvm-commits] CVS: llvm-test/SingleSource/Benchmarks/Misc/Makefile bigfib.cpp Message-ID: <200410051659.LAA19247@apoc.cs.uiuc.edu> Changes in directory llvm-test/SingleSource/Benchmarks/Misc: Makefile updated: 1.4 -> 1.5 bigfib.cpp (r1.1) removed --- Log message: Move C++ test to Misc-C++ --- Diffs of the changes: (+1 -2) Index: llvm-test/SingleSource/Benchmarks/Misc/Makefile diff -u llvm-test/SingleSource/Benchmarks/Misc/Makefile:1.4 llvm-test/SingleSource/Benchmarks/Misc/Makefile:1.5 --- llvm-test/SingleSource/Benchmarks/Misc/Makefile:1.4 Tue Oct 5 11:57:21 2004 +++ llvm-test/SingleSource/Benchmarks/Misc/Makefile Tue Oct 5 11:59:09 2004 @@ -1,6 +1,5 @@ LEVEL = ../../.. -LDFLAGS += -lm -lstdc++ -LIBS = -lstdc++ +LDFLAGS += -lm FP_TOLERANCE := 0.001 include $(LEVEL)/SingleSource/Makefile.singlesrc From lattner at cs.uiuc.edu Tue Oct 5 13:01:17 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:01:17 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/ Message-ID: <200410051801.NAA20353@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 13:01:21 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:01:21 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/ Message-ID: <200410051801.NAA20356@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 13:03:12 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:03:12 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/InstructionCombining.cpp.txt Makefile README agrep agrep.h asearch.c asearch1.c bitap.c checkfile.c checkfile.h compat.c follow.c main.c maskgen.c mgrep.c parse.c preprocess.c re.h sgrep.c utilities.c Message-ID: <200410051803.NAA20600@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep: InstructionCombining.cpp.txt added (r1.1) Makefile added (r1.1) README added (r1.1) agrep added (r1.1) agrep.h added (r1.1) asearch.c added (r1.1) asearch1.c added (r1.1) bitap.c added (r1.1) checkfile.c added (r1.1) checkfile.h added (r1.1) compat.c added (r1.1) follow.c added (r1.1) main.c added (r1.1) maskgen.c added (r1.1) mgrep.c added (r1.1) parse.c added (r1.1) preprocess.c added (r1.1) re.h added (r1.1) sgrep.c added (r1.1) utilities.c added (r1.1) --- Log message: New benchmark --- Diffs of the changes: (+7998 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/InstructionCombining.cpp.txt diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/InstructionCombining.cpp.txt:1.1 *** /dev/null Tue Oct 5 13:03:08 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/InstructionCombining.cpp.txt Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,3936 ---- + //===- InstructionCombining.cpp - Combine multiple instructions -----------===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by the LLVM research group and is distributed under + // the University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // InstructionCombining - Combine instructions to form fewer, simple + // instructions. This pass does not modify the CFG This pass is where algebraic + // simplification happens. + // + // This pass combines things like: + // %Y = add int %X, 1 + // %Z = add int %Y, 1 + // into: + // %Z = add int %X, 2 + // + // This is a simple worklist driven algorithm. + // + // This pass guarantees that the following canonicalizations are performed on + // the program: + // 1. If a binary operator has a constant operand, it is moved to the RHS + // 2. Bitwise operators with constant operands are always grouped so that + // shifts are performed first, then or's, then and's, then xor's. + // 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible + // 4. All SetCC instructions on boolean values are replaced with logical ops + // 5. add X, X is represented as (X*2) => (X << 1) + // 6. Multiplies with a power-of-two constant argument are transformed into + // shifts. + // N. This list is incomplete + // + //===----------------------------------------------------------------------===// + + #define DEBUG_TYPE "instcombine" + #include "llvm/Transforms/Scalar.h" + #include "llvm/Instructions.h" + #include "llvm/Intrinsics.h" + #include "llvm/Pass.h" + #include "llvm/Constants.h" + #include "llvm/DerivedTypes.h" + #include "llvm/GlobalVariable.h" + #include "llvm/Target/TargetData.h" + #include "llvm/Transforms/Utils/BasicBlockUtils.h" + #include "llvm/Transforms/Utils/Local.h" + #include "llvm/Support/CallSite.h" + #include "llvm/Support/GetElementPtrTypeIterator.h" + #include "llvm/Support/InstIterator.h" + #include "llvm/Support/InstVisitor.h" + #include "llvm/Support/PatternMatch.h" + #include "llvm/Support/Debug.h" + #include "llvm/ADT/Statistic.h" + #include + using namespace llvm; + using namespace llvm::PatternMatch; + + namespace { + Statistic<> NumCombined ("instcombine", "Number of insts combined"); + Statistic<> NumConstProp("instcombine", "Number of constant folds"); + Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated"); + + class InstCombiner : public FunctionPass, + public InstVisitor { + // Worklist of all of the instructions that need to be simplified. + std::vector WorkList; + TargetData *TD; + + /// AddUsersToWorkList - When an instruction is simplified, add all users of + /// the instruction to the work lists because they might get more simplified + /// now. + /// + void AddUsersToWorkList(Instruction &I) { + for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); + UI != UE; ++UI) + WorkList.push_back(cast(*UI)); + } + + /// AddUsesToWorkList - When an instruction is simplified, add operands to + /// the work lists because they might get more simplified now. + /// + void AddUsesToWorkList(Instruction &I) { + for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) + if (Instruction *Op = dyn_cast(I.getOperand(i))) + WorkList.push_back(Op); + } + + // removeFromWorkList - remove all instances of I from the worklist. + void removeFromWorkList(Instruction *I); + public: + virtual bool runOnFunction(Function &F); + + virtual void getAnalysisUsage(AnalysisUsage &AU) const { + AU.addRequired(); + AU.setPreservesCFG(); + } + + TargetData &getTargetData() const { return *TD; } + + // Visitation implementation - Implement instruction combining for different + // instruction types. The semantics are as follows: + // Return Value: + // null - No change was made + // I - Change was made, I is still valid, I may be dead though + // otherwise - Change was made, replace I with returned instruction + // + Instruction *visitAdd(BinaryOperator &I); + Instruction *visitSub(BinaryOperator &I); + Instruction *visitMul(BinaryOperator &I); + Instruction *visitDiv(BinaryOperator &I); + Instruction *visitRem(BinaryOperator &I); + Instruction *visitAnd(BinaryOperator &I); + Instruction *visitOr (BinaryOperator &I); + Instruction *visitXor(BinaryOperator &I); + Instruction *visitSetCondInst(BinaryOperator &I); + Instruction *visitShiftInst(ShiftInst &I); + Instruction *visitCastInst(CastInst &CI); + Instruction *visitSelectInst(SelectInst &CI); + Instruction *visitCallInst(CallInst &CI); + Instruction *visitInvokeInst(InvokeInst &II); + Instruction *visitPHINode(PHINode &PN); + Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP); + Instruction *visitAllocationInst(AllocationInst &AI); + Instruction *visitFreeInst(FreeInst &FI); + Instruction *visitLoadInst(LoadInst &LI); + Instruction *visitBranchInst(BranchInst &BI); + Instruction *visitSwitchInst(SwitchInst &SI); + + // visitInstruction - Specify what to return for unhandled instructions... + Instruction *visitInstruction(Instruction &I) { return 0; } + + private: + Instruction *visitCallSite(CallSite CS); + bool transformConstExprCastCall(CallSite CS); + + public: + // InsertNewInstBefore - insert an instruction New before instruction Old + // in the program. Add the new instruction to the worklist. + // + Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) { + assert(New && New->getParent() == 0 && + "New instruction already inserted into a basic block!"); + BasicBlock *BB = Old.getParent(); + BB->getInstList().insert(&Old, New); // Insert inst + WorkList.push_back(New); // Add to worklist + return New; + } + + /// InsertCastBefore - Insert a cast of V to TY before the instruction POS. + /// This also adds the cast to the worklist. Finally, this returns the + /// cast. + Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) { + if (V->getType() == Ty) return V; + + Instruction *C = new CastInst(V, Ty, V->getName(), &Pos); + WorkList.push_back(C); + return C; + } + + // ReplaceInstUsesWith - This method is to be used when an instruction is + // found to be dead, replacable with another preexisting expression. Here + // we add all uses of I to the worklist, replace all uses of I with the new + // value, then return I, so that the inst combiner will know that I was + // modified. + // + Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) { + AddUsersToWorkList(I); // Add all modified instrs to worklist + if (&I != V) { + I.replaceAllUsesWith(V); + return &I; + } else { + // If we are replacing the instruction with itself, this must be in a + // segment of unreachable code, so just clobber the instruction. + I.replaceAllUsesWith(Constant::getNullValue(I.getType())); + return &I; + } + } + + // EraseInstFromFunction - When dealing with an instruction that has side + // effects or produces a void value, we can't rely on DCE to delete the + // instruction. Instead, visit methods should return the value returned by + // this function. + Instruction *EraseInstFromFunction(Instruction &I) { + assert(I.use_empty() && "Cannot erase instruction that is used!"); + AddUsesToWorkList(I); + removeFromWorkList(&I); + I.getParent()->getInstList().erase(&I); + return 0; // Don't do anything with FI + } + + + private: + /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the + /// InsertBefore instruction. This is specialized a bit to avoid inserting + /// casts that are known to not do anything... + /// + Value *InsertOperandCastBefore(Value *V, const Type *DestTy, + Instruction *InsertBefore); + + // SimplifyCommutative - This performs a few simplifications for commutative + // operators. + bool SimplifyCommutative(BinaryOperator &I); + + + // FoldOpIntoPhi - Given a binary operator or cast instruction which has a + // PHI node as operand #0, see if we can fold the instruction into the PHI + // (which is only possible if all operands to the PHI are constants). + Instruction *FoldOpIntoPhi(Instruction &I); + + Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS, + ConstantIntegral *AndRHS, BinaryOperator &TheAnd); + + Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi, + bool Inside, Instruction &IB); + }; + + RegisterOpt X("instcombine", "Combine redundant instructions"); + } + + // getComplexity: Assign a complexity or rank value to LLVM Values... + // 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst + static unsigned getComplexity(Value *V) { + if (isa(V)) { + if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V)) + return 2; + return 3; + } + if (isa(V)) return 2; + return isa(V) ? 0 : 1; + } + + // isOnlyUse - Return true if this instruction will be deleted if we stop using + // it. + static bool isOnlyUse(Value *V) { + return V->hasOneUse() || isa(V); + } + + // getPromotedType - Return the specified type promoted as it would be to pass + // though a va_arg area... + static const Type *getPromotedType(const Type *Ty) { + switch (Ty->getTypeID()) { + case Type::SByteTyID: + case Type::ShortTyID: return Type::IntTy; + case Type::UByteTyID: + case Type::UShortTyID: return Type::UIntTy; + case Type::FloatTyID: return Type::DoubleTy; + default: return Ty; + } + } + + // SimplifyCommutative - This performs a few simplifications for commutative + // operators: + // + // 1. Order operands such that they are listed from right (least complex) to + // left (most complex). This puts constants before unary operators before + // binary operators. + // + // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2)) + // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2)) + // + bool InstCombiner::SimplifyCommutative(BinaryOperator &I) { + bool Changed = false; + if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) + Changed = !I.swapOperands(); + + if (!I.isAssociative()) return Changed; + Instruction::BinaryOps Opcode = I.getOpcode(); + if (BinaryOperator *Op = dyn_cast(I.getOperand(0))) + if (Op->getOpcode() == Opcode && isa(Op->getOperand(1))) { + if (isa(I.getOperand(1))) { + Constant *Folded = ConstantExpr::get(I.getOpcode(), + cast(I.getOperand(1)), + cast(Op->getOperand(1))); + I.setOperand(0, Op->getOperand(0)); + I.setOperand(1, Folded); + return true; + } else if (BinaryOperator *Op1=dyn_cast(I.getOperand(1))) + if (Op1->getOpcode() == Opcode && isa(Op1->getOperand(1)) && + isOnlyUse(Op) && isOnlyUse(Op1)) { + Constant *C1 = cast(Op->getOperand(1)); + Constant *C2 = cast(Op1->getOperand(1)); + + // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2)) + Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2); + Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0), + Op1->getOperand(0), + Op1->getName(), &I); + WorkList.push_back(New); + I.setOperand(0, New); + I.setOperand(1, Folded); + return true; + } + } + return Changed; + } + + // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction + // if the LHS is a constant zero (which is the 'negate' form). + // + static inline Value *dyn_castNegVal(Value *V) { + if (BinaryOperator::isNeg(V)) + return BinaryOperator::getNegArgument(cast(V)); + + // Constants can be considered to be negated values if they can be folded... + if (Constant *C = dyn_cast(V)) + return ConstantExpr::getNeg(C); + return 0; + } + + static inline Value *dyn_castNotVal(Value *V) { + if (BinaryOperator::isNot(V)) + return BinaryOperator::getNotArgument(cast(V)); + + // Constants can be considered to be not'ed values... + if (ConstantIntegral *C = dyn_cast(V)) + return ConstantExpr::getNot(C); + return 0; + } + + // dyn_castFoldableMul - If this value is a multiply that can be folded into + // other computations (because it has a constant operand), return the + // non-constant operand of the multiply. + // + static inline Value *dyn_castFoldableMul(Value *V) { + if (V->hasOneUse() && V->getType()->isInteger()) + if (Instruction *I = dyn_cast(V)) + if (I->getOpcode() == Instruction::Mul) + if (isa(I->getOperand(1))) + return I->getOperand(0); + return 0; + } + + // Log2 - Calculate the log base 2 for the specified value if it is exactly a + // power of 2. + static unsigned Log2(uint64_t Val) { + assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!"); + unsigned Count = 0; + while (Val != 1) { + if (Val & 1) return 0; // Multiple bits set? + Val >>= 1; + ++Count; + } + return Count; + } + + // AddOne, SubOne - Add or subtract a constant one from an integer constant... + static ConstantInt *AddOne(ConstantInt *C) { + return cast(ConstantExpr::getAdd(C, + ConstantInt::get(C->getType(), 1))); + } + static ConstantInt *SubOne(ConstantInt *C) { + return cast(ConstantExpr::getSub(C, + ConstantInt::get(C->getType(), 1))); + } + + // isTrueWhenEqual - Return true if the specified setcondinst instruction is + // true when both operands are equal... + // + static bool isTrueWhenEqual(Instruction &I) { + return I.getOpcode() == Instruction::SetEQ || + I.getOpcode() == Instruction::SetGE || + I.getOpcode() == Instruction::SetLE; + } + + /// AssociativeOpt - Perform an optimization on an associative operator. This + /// function is designed to check a chain of associative operators for a + /// potential to apply a certain optimization. Since the optimization may be + /// applicable if the expression was reassociated, this checks the chain, then + /// reassociates the expression as necessary to expose the optimization + /// opportunity. This makes use of a special Functor, which must define + /// 'shouldApply' and 'apply' methods. + /// + template + Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) { + unsigned Opcode = Root.getOpcode(); + Value *LHS = Root.getOperand(0); + + // Quick check, see if the immediate LHS matches... + if (F.shouldApply(LHS)) + return F.apply(Root); + + // Otherwise, if the LHS is not of the same opcode as the root, return. + Instruction *LHSI = dyn_cast(LHS); + while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) { + // Should we apply this transform to the RHS? + bool ShouldApply = F.shouldApply(LHSI->getOperand(1)); + + // If not to the RHS, check to see if we should apply to the LHS... + if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) { + cast(LHSI)->swapOperands(); // Make the LHS the RHS + ShouldApply = true; + } + + // If the functor wants to apply the optimization to the RHS of LHSI, + // reassociate the expression from ((? op A) op B) to (? op (A op B)) + if (ShouldApply) { + BasicBlock *BB = Root.getParent(); + + // Now all of the instructions are in the current basic block, go ahead + // and perform the reassociation. + Instruction *TmpLHSI = cast(Root.getOperand(0)); + + // First move the selected RHS to the LHS of the root... + Root.setOperand(0, LHSI->getOperand(1)); + + // Make what used to be the LHS of the root be the user of the root... + Value *ExtraOperand = TmpLHSI->getOperand(1); + if (&Root == TmpLHSI) { + Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType())); + return 0; + } + Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI + TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root + TmpLHSI->getParent()->getInstList().remove(TmpLHSI); + BasicBlock::iterator ARI = &Root; ++ARI; + BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root + ARI = Root; + + // Now propagate the ExtraOperand down the chain of instructions until we + // get to LHSI. + while (TmpLHSI != LHSI) { + Instruction *NextLHSI = cast(TmpLHSI->getOperand(0)); + // Move the instruction to immediately before the chain we are + // constructing to avoid breaking dominance properties. + NextLHSI->getParent()->getInstList().remove(NextLHSI); + BB->getInstList().insert(ARI, NextLHSI); + ARI = NextLHSI; + + Value *NextOp = NextLHSI->getOperand(1); + NextLHSI->setOperand(1, ExtraOperand); + TmpLHSI = NextLHSI; + ExtraOperand = NextOp; + } + + // Now that the instructions are reassociated, have the functor perform + // the transformation... + return F.apply(Root); + } + + LHSI = dyn_cast(LHSI->getOperand(0)); + } + return 0; + } + + + // AddRHS - Implements: X + X --> X << 1 + struct AddRHS { + Value *RHS; + AddRHS(Value *rhs) : RHS(rhs) {} + bool shouldApply(Value *LHS) const { return LHS == RHS; } + Instruction *apply(BinaryOperator &Add) const { + return new ShiftInst(Instruction::Shl, Add.getOperand(0), + ConstantInt::get(Type::UByteTy, 1)); + } + }; + + // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2) + // iff C1&C2 == 0 + struct AddMaskingAnd { + Constant *C2; + AddMaskingAnd(Constant *c) : C2(c) {} + bool shouldApply(Value *LHS) const { + ConstantInt *C1; + return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) && + ConstantExpr::getAnd(C1, C2)->isNullValue(); + } + Instruction *apply(BinaryOperator &Add) const { + return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1)); + } + }; + + static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO, + InstCombiner *IC) { + // Figure out if the constant is the left or the right argument. + bool ConstIsRHS = isa(BI.getOperand(1)); + Constant *ConstOperand = cast(BI.getOperand(ConstIsRHS)); + + if (Constant *SOC = dyn_cast(SO)) { + if (ConstIsRHS) + return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand); + return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC); + } + + Value *Op0 = SO, *Op1 = ConstOperand; + if (!ConstIsRHS) + std::swap(Op0, Op1); + Instruction *New; + if (BinaryOperator *BO = dyn_cast(&BI)) + New = BinaryOperator::create(BO->getOpcode(), Op0, Op1); + else if (ShiftInst *SI = dyn_cast(&BI)) + New = new ShiftInst(SI->getOpcode(), Op0, Op1); + else { + assert(0 && "Unknown binary instruction type!"); + abort(); + } + return IC->InsertNewInstBefore(New, BI); + } + + + /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI + /// node as operand #0, see if we can fold the instruction into the PHI (which + /// is only possible if all operands to the PHI are constants). + Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) { + PHINode *PN = cast(I.getOperand(0)); + if (!PN->hasOneUse()) return 0; + + // Check to see if all of the operands of the PHI are constants. If not, we + // cannot do the transformation. + for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) + if (!isa(PN->getIncomingValue(i))) + return 0; + + // Okay, we can do the transformation: create the new PHI node. + PHINode *NewPN = new PHINode(I.getType(), I.getName()); + I.setName(""); + NewPN->op_reserve(PN->getNumOperands()); + InsertNewInstBefore(NewPN, *PN); + + // Next, add all of the operands to the PHI. + if (I.getNumOperands() == 2) { + Constant *C = cast(I.getOperand(1)); + for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { + Constant *InV = cast(PN->getIncomingValue(i)); + NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C), + PN->getIncomingBlock(i)); + } + } else { + assert(isa(I) && "Unary op should be a cast!"); + const Type *RetTy = I.getType(); + for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { + Constant *InV = cast(PN->getIncomingValue(i)); + NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy), + PN->getIncomingBlock(i)); + } + } + return ReplaceInstUsesWith(I, NewPN); + } + + // FoldBinOpIntoSelect - Given an instruction with a select as one operand and a + // constant as the other operand, try to fold the binary operator into the + // select arguments. + static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI, + InstCombiner *IC) { + // Don't modify shared select instructions + if (!SI->hasOneUse()) return 0; + Value *TV = SI->getOperand(1); + Value *FV = SI->getOperand(2); + + if (isa(TV) || isa(FV)) { + Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC); + Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC); + + return new SelectInst(SI->getCondition(), SelectTrueVal, + SelectFalseVal); + } + return 0; + } + + Instruction *InstCombiner::visitAdd(BinaryOperator &I) { + bool Changed = SimplifyCommutative(I); + Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); + + if (Constant *RHSC = dyn_cast(RHS)) { + // X + 0 --> X + if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop + RHSC->isNullValue()) + return ReplaceInstUsesWith(I, LHS); + + // X + (signbit) --> X ^ signbit + if (ConstantInt *CI = dyn_cast(RHSC)) { + unsigned NumBits = CI->getType()->getPrimitiveSize()*8; + uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1; + if (Val == (1ULL << NumBits-1)) + return BinaryOperator::createXor(LHS, RHS); + } + + if (isa(LHS)) + if (Instruction *NV = FoldOpIntoPhi(I)) + return NV; + } + + // X + X --> X << 1 + if (I.getType()->isInteger()) { + if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result; + } + + // -A + B --> B - A + if (Value *V = dyn_castNegVal(LHS)) + return BinaryOperator::createSub(RHS, V); + + // A + -B --> A - B + if (!isa(RHS)) + if (Value *V = dyn_castNegVal(RHS)) + return BinaryOperator::createSub(LHS, V); + + // X*C + X --> X * (C+1) + if (dyn_castFoldableMul(LHS) == RHS) { + Constant *CP1 = + ConstantExpr::getAdd( + cast(cast(LHS)->getOperand(1)), + ConstantInt::get(I.getType(), 1)); + return BinaryOperator::createMul(RHS, CP1); + } + + // X + X*C --> X * (C+1) + if (dyn_castFoldableMul(RHS) == LHS) { + Constant *CP1 = + ConstantExpr::getAdd( + cast(cast(RHS)->getOperand(1)), + ConstantInt::get(I.getType(), 1)); + return BinaryOperator::createMul(LHS, CP1); + } + + // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0 + ConstantInt *C2; + if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)))) + if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R; + + if (ConstantInt *CRHS = dyn_cast(RHS)) { + Value *X; + if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X + Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1)); + return BinaryOperator::createSub(C, X); + } + + // Try to fold constant add into select arguments. + if (SelectInst *SI = dyn_cast(LHS)) + if (Instruction *R = FoldBinOpIntoSelect(I, SI, this)) + return R; + } + + return Changed ? &I : 0; + } + + // isSignBit - Return true if the value represented by the constant only has the + // highest order bit set. + static bool isSignBit(ConstantInt *CI) { + unsigned NumBits = CI->getType()->getPrimitiveSize()*8; + return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1)); + } + + static unsigned getTypeSizeInBits(const Type *Ty) { + return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8; + } + + /// RemoveNoopCast - Strip off nonconverting casts from the value. + /// + static Value *RemoveNoopCast(Value *V) { + if (CastInst *CI = dyn_cast(V)) { + const Type *CTy = CI->getType(); + const Type *OpTy = CI->getOperand(0)->getType(); + if (CTy->isInteger() && OpTy->isInteger()) { + if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize()) + return RemoveNoopCast(CI->getOperand(0)); + } else if (isa(CTy) && isa(OpTy)) + return RemoveNoopCast(CI->getOperand(0)); + } + return V; + } + + Instruction *InstCombiner::visitSub(BinaryOperator &I) { + Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); + + if (Op0 == Op1) // sub X, X -> 0 + return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); + + // If this is a 'B = x-(-A)', change to B = x+A... + if (Value *V = dyn_castNegVal(Op1)) + return BinaryOperator::createAdd(Op0, V); + + if (ConstantInt *C = dyn_cast(Op0)) { + // Replace (-1 - A) with (~A)... + if (C->isAllOnesValue()) + return BinaryOperator::createNot(Op1); + + // C - ~X == X + (1+C) + Value *X; + if (match(Op1, m_Not(m_Value(X)))) + return BinaryOperator::createAdd(X, + ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1))); + // -((uint)X >> 31) -> ((int)X >> 31) + // -((int)X >> 31) -> ((uint)X >> 31) + if (C->isNullValue()) { + Value *NoopCastedRHS = RemoveNoopCast(Op1); + if (ShiftInst *SI = dyn_cast(NoopCastedRHS)) + if (SI->getOpcode() == Instruction::Shr) + if (ConstantUInt *CU = dyn_cast(SI->getOperand(1))) { + const Type *NewTy; + if (SI->getType()->isSigned()) + NewTy = SI->getType()->getUnsignedVersion(); + else + NewTy = SI->getType()->getSignedVersion(); + // Check to see if we are shifting out everything but the sign bit. + if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) { + // Ok, the transformation is safe. Insert a cast of the incoming + // value, then the new shift, then the new cast. + Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy, + SI->getOperand(0)->getName()); + Value *InV = InsertNewInstBefore(FirstCast, I); + Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast, + CU, SI->getName()); + if (NewShift->getType() == I.getType()) + return NewShift; + else { + InV = InsertNewInstBefore(NewShift, I); + return new CastInst(NewShift, I.getType()); + } + } + } + } + + // Try to fold constant sub into select arguments. + if (SelectInst *SI = dyn_cast(Op1)) + if (Instruction *R = FoldBinOpIntoSelect(I, SI, this)) + return R; + + if (isa(Op0)) + if (Instruction *NV = FoldOpIntoPhi(I)) + return NV; + } + + if (BinaryOperator *Op1I = dyn_cast(Op1)) + if (Op1I->hasOneUse()) { + // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression + // is not used by anyone else... + // + if (Op1I->getOpcode() == Instruction::Sub && + !Op1I->getType()->isFloatingPoint()) { + // Swap the two operands of the subexpr... + Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1); + Op1I->setOperand(0, IIOp1); + Op1I->setOperand(1, IIOp0); + + // Create the new top level add instruction... + return BinaryOperator::createAdd(Op0, Op1); + } + + // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)... + // + if (Op1I->getOpcode() == Instruction::And && + (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) { + Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0); + + Value *NewNot = + InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I); + return BinaryOperator::createAnd(Op0, NewNot); + } + + // X - X*C --> X * (1-C) + if (dyn_castFoldableMul(Op1I) == Op0) { + Constant *CP1 = + ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), + cast(cast(Op1)->getOperand(1))); + assert(CP1 && "Couldn't constant fold 1-C?"); + return BinaryOperator::createMul(Op0, CP1); + } + } + + // X*C - X --> X * (C-1) + if (dyn_castFoldableMul(Op0) == Op1) { + Constant *CP1 = + ConstantExpr::getSub(cast(cast(Op0)->getOperand(1)), + ConstantInt::get(I.getType(), 1)); + assert(CP1 && "Couldn't constant fold C - 1?"); + return BinaryOperator::createMul(Op1, CP1); + } + + return 0; + } + + /// isSignBitCheck - Given an exploded setcc instruction, return true if it is + /// really just returns true if the most significant (sign) bit is set. + static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) { + if (RHS->getType()->isSigned()) { + // True if source is LHS < 0 or LHS <= -1 + return Opcode == Instruction::SetLT && RHS->isNullValue() || + Opcode == Instruction::SetLE && RHS->isAllOnesValue(); + } else { + ConstantUInt *RHSC = cast(RHS); + // True if source is LHS > 127 or LHS >= 128, where the constants depend on + // the size of the integer type. + if (Opcode == Instruction::SetGE) + return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1); + if (Opcode == Instruction::SetGT) + return RHSC->getValue() == + (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1; + } + return false; + } + + Instruction *InstCombiner::visitMul(BinaryOperator &I) { + bool Changed = SimplifyCommutative(I); + Value *Op0 = I.getOperand(0); + + // Simplify mul instructions with a constant RHS... + if (Constant *Op1 = dyn_cast(I.getOperand(1))) { + if (ConstantInt *CI = dyn_cast(Op1)) { + + // ((X << C1)*C2) == (X * (C2 << C1)) + if (ShiftInst *SI = dyn_cast(Op0)) + if (SI->getOpcode() == Instruction::Shl) + if (Constant *ShOp = dyn_cast(SI->getOperand(1))) + return BinaryOperator::createMul(SI->getOperand(0), + ConstantExpr::getShl(CI, ShOp)); + + if (CI->isNullValue()) + return ReplaceInstUsesWith(I, Op1); // X * 0 == 0 + if (CI->equalsInt(1)) // X * 1 == X + return ReplaceInstUsesWith(I, Op0); + if (CI->isAllOnesValue()) // X * -1 == 0 - X + return BinaryOperator::createNeg(Op0, I.getName()); + + int64_t Val = (int64_t)cast(CI)->getRawValue(); + if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C + return new ShiftInst(Instruction::Shl, Op0, + ConstantUInt::get(Type::UByteTy, C)); + } else if (ConstantFP *Op1F = dyn_cast(Op1)) { + if (Op1F->isNullValue()) + return ReplaceInstUsesWith(I, Op1); + + // "In IEEE floating point, x*1 is not equivalent to x for nans. However, + // ANSI says we can drop signals, so we can do this anyway." (from GCC) + if (Op1F->getValue() == 1.0) + return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0' + } + + // Try to fold constant mul into select arguments. + if (SelectInst *SI = dyn_cast(Op0)) + if (Instruction *R = FoldBinOpIntoSelect(I, SI, this)) + return R; + + if (isa(Op0)) + if (Instruction *NV = FoldOpIntoPhi(I)) + return NV; + } + + if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y + if (Value *Op1v = dyn_castNegVal(I.getOperand(1))) + return BinaryOperator::createMul(Op0v, Op1v); + + // If one of the operands of the multiply is a cast from a boolean value, then + // we know the bool is either zero or one, so this is a 'masking' multiply. + // See if we can simplify things based on how the boolean was originally + // formed. + CastInst *BoolCast = 0; + if (CastInst *CI = dyn_cast(I.getOperand(0))) + if (CI->getOperand(0)->getType() == Type::BoolTy) + BoolCast = CI; + if (!BoolCast) + if (CastInst *CI = dyn_cast(I.getOperand(1))) + if (CI->getOperand(0)->getType() == Type::BoolTy) + BoolCast = CI; + if (BoolCast) { + if (SetCondInst *SCI = dyn_cast(BoolCast->getOperand(0))) { + Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1); + const Type *SCOpTy = SCIOp0->getType(); + + // If the setcc is true iff the sign bit of X is set, then convert this + // multiply into a shift/and combination. + if (isa(SCIOp1) && + isSignBitCheck(SCI->getOpcode(), SCIOp0, cast(SCIOp1))) { + // Shift the X value right to turn it into "all signbits". + Constant *Amt = ConstantUInt::get(Type::UByteTy, + SCOpTy->getPrimitiveSize()*8-1); + if (SCIOp0->getType()->isUnsigned()) { + const Type *NewTy = SCIOp0->getType()->getSignedVersion(); + SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy, + SCIOp0->getName()), I); + } + + Value *V = + InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt, + BoolCast->getOperand(0)->getName()+ + ".mask"), I); + + // If the multiply type is not the same as the source type, sign extend + // or truncate to the multiply type. + if (I.getType() != V->getType()) + V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I); + + Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0; + return BinaryOperator::createAnd(V, OtherOp); + } + } + } + + return Changed ? &I : 0; + } + + Instruction *InstCombiner::visitDiv(BinaryOperator &I) { + if (ConstantInt *RHS = dyn_cast(I.getOperand(1))) { + // div X, 1 == X + if (RHS->equalsInt(1)) + return ReplaceInstUsesWith(I, I.getOperand(0)); + + // div X, -1 == -X + if (RHS->isAllOnesValue()) + return BinaryOperator::createNeg(I.getOperand(0)); + + if (Instruction *LHS = dyn_cast(I.getOperand(0))) + if (LHS->getOpcode() == Instruction::Div) + if (ConstantInt *LHSRHS = dyn_cast(LHS->getOperand(1))) { + // (X / C1) / C2 -> X / (C1*C2) + return BinaryOperator::createDiv(LHS->getOperand(0), + ConstantExpr::getMul(RHS, LHSRHS)); + } + + // Check to see if this is an unsigned division with an exact power of 2, + // if so, convert to a right shift. + if (ConstantUInt *C = dyn_cast(RHS)) + if (uint64_t Val = C->getValue()) // Don't break X / 0 + if (uint64_t C = Log2(Val)) + return new ShiftInst(Instruction::Shr, I.getOperand(0), + ConstantUInt::get(Type::UByteTy, C)); + + if (isa(I.getOperand(0)) && !RHS->isNullValue()) + if (Instruction *NV = FoldOpIntoPhi(I)) + return NV; + } + + // 0 / X == 0, we don't need to preserve faults! + if (ConstantInt *LHS = dyn_cast(I.getOperand(0))) + if (LHS->equalsInt(0)) + return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); + + return 0; + } + + + Instruction *InstCombiner::visitRem(BinaryOperator &I) { + if (I.getType()->isSigned()) + if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1))) + if (!isa(RHSNeg) || + cast(RHSNeg)->getValue() > 0) { + // X % -Y -> X % Y + AddUsesToWorkList(I); + I.setOperand(1, RHSNeg); + return &I; + } + + if (ConstantInt *RHS = dyn_cast(I.getOperand(1))) { + if (RHS->equalsInt(1)) // X % 1 == 0 + return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); + + // Check to see if this is an unsigned remainder with an exact power of 2, + // if so, convert to a bitwise and. + if (ConstantUInt *C = dyn_cast(RHS)) + if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero) + if (!(Val & (Val-1))) // Power of 2 + return BinaryOperator::createAnd(I.getOperand(0), + ConstantUInt::get(I.getType(), Val-1)); + if (isa(I.getOperand(0)) && !RHS->isNullValue()) + if (Instruction *NV = FoldOpIntoPhi(I)) + return NV; + } + + // 0 % X == 0, we don't need to preserve faults! + if (ConstantInt *LHS = dyn_cast(I.getOperand(0))) + if (LHS->equalsInt(0)) + return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); + + return 0; + } + + // isMaxValueMinusOne - return true if this is Max-1 + static bool isMaxValueMinusOne(const ConstantInt *C) { + if (const ConstantUInt *CU = dyn_cast(C)) { + // Calculate -1 casted to the right type... + unsigned TypeBits = C->getType()->getPrimitiveSize()*8; + uint64_t Val = ~0ULL; // All ones + Val >>= 64-TypeBits; // Shift out unwanted 1 bits... + return CU->getValue() == Val-1; + } + + const ConstantSInt *CS = cast(C); + + // Calculate 0111111111..11111 + unsigned TypeBits = C->getType()->getPrimitiveSize()*8; + int64_t Val = INT64_MAX; // All ones + Val >>= 64-TypeBits; // Shift out unwanted 1 bits... + return CS->getValue() == Val-1; + } + + // isMinValuePlusOne - return true if this is Min+1 + static bool isMinValuePlusOne(const ConstantInt *C) { + if (const ConstantUInt *CU = dyn_cast(C)) + return CU->getValue() == 1; + + const ConstantSInt *CS = cast(C); + + // Calculate 1111111111000000000000 + unsigned TypeBits = C->getType()->getPrimitiveSize()*8; + int64_t Val = -1; // All ones + Val <<= TypeBits-1; // Shift over to the right spot + return CS->getValue() == Val+1; + } + + // isOneBitSet - Return true if there is exactly one bit set in the specified + // constant. + static bool isOneBitSet(const ConstantInt *CI) { + uint64_t V = CI->getRawValue(); + return V && (V & (V-1)) == 0; + } + + #if 0 // Currently unused + // isLowOnes - Return true if the constant is of the form 0+1+. + static bool isLowOnes(const ConstantInt *CI) { + uint64_t V = CI->getRawValue(); + + // There won't be bits set in parts that the type doesn't contain. + V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue(); + + uint64_t U = V+1; // If it is low ones, this should be a power of two. + return U && V && (U & V) == 0; + } + #endif + + // isHighOnes - Return true if the constant is of the form 1+0+. + // This is the same as lowones(~X). + static bool isHighOnes(const ConstantInt *CI) { + uint64_t V = ~CI->getRawValue(); + + // There won't be bits set in parts that the type doesn't contain. + V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue(); + + uint64_t U = V+1; // If it is low ones, this should be a power of two. + return U && V && (U & V) == 0; + } + + + /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits + /// are carefully arranged to allow folding of expressions such as: + /// + /// (A < B) | (A > B) --> (A != B) + /// + /// Bit value '4' represents that the comparison is true if A > B, bit value '2' + /// represents that the comparison is true if A == B, and bit value '1' is true + /// if A < B. + /// + static unsigned getSetCondCode(const SetCondInst *SCI) { + switch (SCI->getOpcode()) { + // False -> 0 + case Instruction::SetGT: return 1; + case Instruction::SetEQ: return 2; + case Instruction::SetGE: return 3; + case Instruction::SetLT: return 4; + case Instruction::SetNE: return 5; + case Instruction::SetLE: return 6; + // True -> 7 + default: + assert(0 && "Invalid SetCC opcode!"); + return 0; + } + } + + /// getSetCCValue - This is the complement of getSetCondCode, which turns an + /// opcode and two operands into either a constant true or false, or a brand new + /// SetCC instruction. + static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) { + switch (Opcode) { + case 0: return ConstantBool::False; + case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS); + case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS); + case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS); + case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS); + case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS); + case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS); + case 7: return ConstantBool::True; + default: assert(0 && "Illegal SetCCCode!"); return 0; + } + } + + // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B) + struct FoldSetCCLogical { + InstCombiner &IC; + Value *LHS, *RHS; + FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI) + : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {} + bool shouldApply(Value *V) const { + if (SetCondInst *SCI = dyn_cast(V)) + return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS || + SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS); + return false; + } + Instruction *apply(BinaryOperator &Log) const { + SetCondInst *SCI = cast(Log.getOperand(0)); + if (SCI->getOperand(0) != LHS) { + assert(SCI->getOperand(1) == LHS); + SCI->swapOperands(); // Swap the LHS and RHS of the SetCC + } + + unsigned LHSCode = getSetCondCode(SCI); + unsigned RHSCode = getSetCondCode(cast(Log.getOperand(1))); + unsigned Code; + switch (Log.getOpcode()) { + case Instruction::And: Code = LHSCode & RHSCode; break; + case Instruction::Or: Code = LHSCode | RHSCode; break; + case Instruction::Xor: Code = LHSCode ^ RHSCode; break; + default: assert(0 && "Illegal logical opcode!"); return 0; + } + + Value *RV = getSetCCValue(Code, LHS, RHS); + if (Instruction *I = dyn_cast(RV)) + return I; + // Otherwise, it's a constant boolean value... + return IC.ReplaceInstUsesWith(Log, RV); + } + }; + + + // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where + // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is + // guaranteed to be either a shift instruction or a binary operator. + Instruction *InstCombiner::OptAndOp(Instruction *Op, + ConstantIntegral *OpRHS, + ConstantIntegral *AndRHS, + BinaryOperator &TheAnd) { + Value *X = Op->getOperand(0); + Constant *Together = 0; + if (!isa(Op)) + Together = ConstantExpr::getAnd(AndRHS, OpRHS); + + switch (Op->getOpcode()) { + case Instruction::Xor: + if (Together->isNullValue()) { + // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0 + return BinaryOperator::createAnd(X, AndRHS); + } else if (Op->hasOneUse()) { + // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2) + std::string OpName = Op->getName(); Op->setName(""); + Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName); + InsertNewInstBefore(And, TheAnd); + return BinaryOperator::createXor(And, Together); + } + break; + case Instruction::Or: + // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0 + if (Together->isNullValue()) + return BinaryOperator::createAnd(X, AndRHS); + else { + if (Together == AndRHS) // (X | C) & C --> C + return ReplaceInstUsesWith(TheAnd, AndRHS); + + if (Op->hasOneUse() && Together != OpRHS) { + // (X | C1) & C2 --> (X | (C1&C2)) & C2 + std::string Op0Name = Op->getName(); Op->setName(""); + Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name); + InsertNewInstBefore(Or, TheAnd); + return BinaryOperator::createAnd(Or, AndRHS); + } + } + break; + case Instruction::Add: + if (Op->hasOneUse()) { + // Adding a one to a single bit bit-field should be turned into an XOR + // of the bit. First thing to check is to see if this AND is with a + // single bit constant. + uint64_t AndRHSV = cast(AndRHS)->getRawValue(); + + // Clear bits that are not part of the constant. + AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1; + + // If there is only one bit set... + if (isOneBitSet(cast(AndRHS))) { + // Ok, at this point, we know that we are masking the result of the + // ADD down to exactly one bit. If the constant we are adding has + // no bits set below this bit, then we can eliminate the ADD. + uint64_t AddRHS = cast(OpRHS)->getRawValue(); + + // Check to see if any bits below the one bit set in AndRHSV are set. + if ((AddRHS & (AndRHSV-1)) == 0) { + // If not, the only thing that can effect the output of the AND is + // the bit specified by AndRHSV. If that bit is set, the effect of + // the XOR is to toggle the bit. If it is clear, then the ADD has + // no effect. + if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop + TheAnd.setOperand(0, X); + return &TheAnd; + } else { + std::string Name = Op->getName(); Op->setName(""); + // Pull the XOR out of the AND. + Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name); + InsertNewInstBefore(NewAnd, TheAnd); + return BinaryOperator::createXor(NewAnd, AndRHS); + } + } + } + } + break; + + case Instruction::Shl: { + // We know that the AND will not produce any of the bits shifted in, so if + // the anded constant includes them, clear them now! + // + Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType()); + Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS); + Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask); + + if (CI == ShlMask) { // Masking out bits that the shift already masks + return ReplaceInstUsesWith(TheAnd, Op); // No need for the and. + } else if (CI != AndRHS) { // Reducing bits set in and. + TheAnd.setOperand(1, CI); + return &TheAnd; + } + break; + } + case Instruction::Shr: + // We know that the AND will not produce any of the bits shifted in, so if + // the anded constant includes them, clear them now! This only applies to + // unsigned shifts, because a signed shr may bring in set bits! + // + if (AndRHS->getType()->isUnsigned()) { + Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType()); + Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS); + Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask); + + if (CI == ShrMask) { // Masking out bits that the shift already masks. + return ReplaceInstUsesWith(TheAnd, Op); + } else if (CI != AndRHS) { + TheAnd.setOperand(1, CI); // Reduce bits set in and cst. + return &TheAnd; + } + } else { // Signed shr. + // See if this is shifting in some sign extension, then masking it out + // with an and. + if (Op->hasOneUse()) { + Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType()); + Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS); + Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask); + if (CI == ShrMask) { // Masking out bits shifted in. + // Make the argument unsigned. + Value *ShVal = Op->getOperand(0); + ShVal = InsertCastBefore(ShVal, + ShVal->getType()->getUnsignedVersion(), + TheAnd); + ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal, + OpRHS, Op->getName()), + TheAnd); + return new CastInst(ShVal, Op->getType()); + } + } + } + break; + } + return 0; + } + + + /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is + /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient + /// (V-Lo) (ConstantExpr::getSetLE(Lo, Hi))->getValue() && + "Lo is not <= Hi in range emission code!"); + if (Inside) { + if (Lo == Hi) // Trivially false. + return new SetCondInst(Instruction::SetNE, V, V); + if (cast(Lo)->isMinValue()) + return new SetCondInst(Instruction::SetLT, V, Hi); + + Constant *AddCST = ConstantExpr::getNeg(Lo); + Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off"); + InsertNewInstBefore(Add, IB); + // Convert to unsigned for the comparison. + const Type *UnsType = Add->getType()->getUnsignedVersion(); + Value *OffsetVal = InsertCastBefore(Add, UnsType, IB); + AddCST = ConstantExpr::getAdd(AddCST, Hi); + AddCST = ConstantExpr::getCast(AddCST, UnsType); + return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST); + } + + if (Lo == Hi) // Trivially true. + return new SetCondInst(Instruction::SetEQ, V, V); + + Hi = SubOne(cast(Hi)); + if (cast(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1' + return new SetCondInst(Instruction::SetGT, V, Hi); + + // Emit X-Lo > Hi-Lo-1 + Constant *AddCST = ConstantExpr::getNeg(Lo); + Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off"); + InsertNewInstBefore(Add, IB); + // Convert to unsigned for the comparison. + const Type *UnsType = Add->getType()->getUnsignedVersion(); + Value *OffsetVal = InsertCastBefore(Add, UnsType, IB); + AddCST = ConstantExpr::getAdd(AddCST, Hi); + AddCST = ConstantExpr::getCast(AddCST, UnsType); + return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST); + } + + + Instruction *InstCombiner::visitAnd(BinaryOperator &I) { + bool Changed = SimplifyCommutative(I); + Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); + + // and X, X = X and X, 0 == 0 + if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType())) + return ReplaceInstUsesWith(I, Op1); + + // and X, -1 == X + if (ConstantIntegral *RHS = dyn_cast(Op1)) { + if (RHS->isAllOnesValue()) + return ReplaceInstUsesWith(I, Op0); + + // Optimize a variety of ((val OP C1) & C2) combinations... + if (isa(Op0) || isa(Op0)) { + Instruction *Op0I = cast(Op0); + Value *X = Op0I->getOperand(0); + if (ConstantInt *Op0CI = dyn_cast(Op0I->getOperand(1))) + if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I)) + return Res; + } + + // Try to fold constant and into select arguments. + if (SelectInst *SI = dyn_cast(Op0)) + if (Instruction *R = FoldBinOpIntoSelect(I, SI, this)) + return R; + if (isa(Op0)) + if (Instruction *NV = FoldOpIntoPhi(I)) + return NV; + } + + Value *Op0NotVal = dyn_castNotVal(Op0); + Value *Op1NotVal = dyn_castNotVal(Op1); + + if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0 + return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); + + // (~A & ~B) == (~(A | B)) - De Morgan's Law + if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) { + Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal, + I.getName()+".demorgan"); + InsertNewInstBefore(Or, I); + return BinaryOperator::createNot(Or); + } + + if (SetCondInst *RHS = dyn_cast(Op1)) { + // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B) + if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS))) + return R; + + Value *LHSVal, *RHSVal; + ConstantInt *LHSCst, *RHSCst; + Instruction::BinaryOps LHSCC, RHSCC; + if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst)))) + if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst)))) + if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2) + // Set[GL]E X, CST is folded to Set[GL]T elsewhere. + LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE && + RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) { + // Ensure that the larger constant is on the RHS. + Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst); + SetCondInst *LHS = cast(Op0); + if (cast(Cmp)->getValue()) { + std::swap(LHS, RHS); + std::swap(LHSCst, RHSCst); + std::swap(LHSCC, RHSCC); + } + + // At this point, we know we have have two setcc instructions + // comparing a value against two constants and and'ing the result + // together. Because of the above check, we know that we only have + // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the + // FoldSetCCLogical check above), that the two constants are not + // equal. + assert(LHSCst != RHSCst && "Compares not folded above?"); + + switch (LHSCC) { + default: assert(0 && "Unknown integer condition code!"); + case Instruction::SetEQ: + switch (RHSCC) { + default: assert(0 && "Unknown integer condition code!"); + case Instruction::SetEQ: // (X == 13 & X == 15) -> false + case Instruction::SetGT: // (X == 13 & X > 15) -> false + return ReplaceInstUsesWith(I, ConstantBool::False); + case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13 + case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13 + return ReplaceInstUsesWith(I, LHS); + } + case Instruction::SetNE: + switch (RHSCC) { + default: assert(0 && "Unknown integer condition code!"); + case Instruction::SetLT: + if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13 + return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst); + break; // (X != 13 & X < 15) -> no change + case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15 + case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15 + return ReplaceInstUsesWith(I, RHS); + case Instruction::SetNE: + if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1 + Constant *AddCST = ConstantExpr::getNeg(LHSCst); + Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST, + LHSVal->getName()+".off"); + InsertNewInstBefore(Add, I); + const Type *UnsType = Add->getType()->getUnsignedVersion(); + Value *OffsetVal = InsertCastBefore(Add, UnsType, I); + AddCST = ConstantExpr::getSub(RHSCst, LHSCst); + AddCST = ConstantExpr::getCast(AddCST, UnsType); + return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST); + } + break; // (X != 13 & X != 15) -> no change + } + break; + case Instruction::SetLT: + switch (RHSCC) { + default: assert(0 && "Unknown integer condition code!"); + case Instruction::SetEQ: // (X < 13 & X == 15) -> false + case Instruction::SetGT: // (X < 13 & X > 15) -> false + return ReplaceInstUsesWith(I, ConstantBool::False); + case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13 + case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13 + return ReplaceInstUsesWith(I, LHS); + } + case Instruction::SetGT: + switch (RHSCC) { + default: assert(0 && "Unknown integer condition code!"); + case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13 + return ReplaceInstUsesWith(I, LHS); + case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15 + return ReplaceInstUsesWith(I, RHS); + case Instruction::SetNE: + if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14 + return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst); + break; // (X > 13 & X != 15) -> no change + case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) (Op1)) { + if (RHS->isAllOnesValue()) + return ReplaceInstUsesWith(I, Op1); + + ConstantInt *C1; Value *X; + // (X & C1) | C2 --> (X | C2) & (C1|C2) + if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) { + std::string Op0Name = Op0->getName(); Op0->setName(""); + Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name); + InsertNewInstBefore(Or, I); + return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1)); + } + + // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2) + if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) { + std::string Op0Name = Op0->getName(); Op0->setName(""); + Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name); + InsertNewInstBefore(Or, I); + return BinaryOperator::createXor(Or, + ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS))); + } + + // Try to fold constant and into select arguments. + if (SelectInst *SI = dyn_cast(Op0)) + if (Instruction *R = FoldBinOpIntoSelect(I, SI, this)) + return R; + if (isa(Op0)) + if (Instruction *NV = FoldOpIntoPhi(I)) + return NV; + } + + // (A & C1)|(A & C2) == A & (C1|C2) + Value *A, *B; ConstantInt *C1, *C2; + if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) && + match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B) + return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2)); + + if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1 + if (A == Op1) // ~A | A == -1 + return ReplaceInstUsesWith(I, + ConstantIntegral::getAllOnesValue(I.getType())); + } else { + A = 0; + } + + if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B + if (Op0 == B) + return ReplaceInstUsesWith(I, + ConstantIntegral::getAllOnesValue(I.getType())); + + // (~A | ~B) == (~(A & B)) - De Morgan's Law + if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) { + Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B, + I.getName()+".demorgan"), I); + return BinaryOperator::createNot(And); + } + } + + // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B) + if (SetCondInst *RHS = dyn_cast(I.getOperand(1))) { + if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS))) + return R; + + Value *LHSVal, *RHSVal; + ConstantInt *LHSCst, *RHSCst; + Instruction::BinaryOps LHSCC, RHSCC; + if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst)))) + if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst)))) + if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2) + // Set[GL]E X, CST is folded to Set[GL]T elsewhere. + LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE && + RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) { + // Ensure that the larger constant is on the RHS. + Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst); + SetCondInst *LHS = cast(Op0); + if (cast(Cmp)->getValue()) { + std::swap(LHS, RHS); + std::swap(LHSCst, RHSCst); + std::swap(LHSCC, RHSCC); + } + + // At this point, we know we have have two setcc instructions + // comparing a value against two constants and or'ing the result + // together. Because of the above check, we know that we only have + // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the + // FoldSetCCLogical check above), that the two constants are not + // equal. + assert(LHSCst != RHSCst && "Compares not folded above?"); + + switch (LHSCC) { + default: assert(0 && "Unknown integer condition code!"); + case Instruction::SetEQ: + switch (RHSCC) { + default: assert(0 && "Unknown integer condition code!"); + case Instruction::SetEQ: + if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 getName()+".off"); + InsertNewInstBefore(Add, I); + const Type *UnsType = Add->getType()->getUnsignedVersion(); + Value *OffsetVal = InsertCastBefore(Add, UnsType, I); + AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst); + AddCST = ConstantExpr::getCast(AddCST, UnsType); + return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST); + } + break; // (X == 13 | X == 15) -> no change + + case Instruction::SetGT: + if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13 + return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst); + break; // (X == 13 | X > 15) -> no change + case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15 + case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15 + return ReplaceInstUsesWith(I, RHS); + } + break; + case Instruction::SetNE: + switch (RHSCC) { + default: assert(0 && "Unknown integer condition code!"); + case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15 + return ReplaceInstUsesWith(I, RHS); + case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13 + case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13 + return ReplaceInstUsesWith(I, LHS); + case Instruction::SetNE: // (X != 13 | X != 15) -> true + return ReplaceInstUsesWith(I, ConstantBool::True); + } + break; + case Instruction::SetLT: + switch (RHSCC) { + default: assert(0 && "Unknown integer condition code!"); + case Instruction::SetEQ: // (X < 13 | X == 14) -> no change + break; + case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2 + return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I); + case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15 + case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15 + return ReplaceInstUsesWith(I, RHS); + } + break; + case Instruction::SetGT: + switch (RHSCC) { + default: assert(0 && "Unknown integer condition code!"); + case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13 + case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13 + return ReplaceInstUsesWith(I, LHS); + case Instruction::SetNE: // (X > 13 | X != 15) -> true + case Instruction::SetLT: // (X > 13 | X < 15) -> true + return ReplaceInstUsesWith(I, ConstantBool::True); + } + } + } + } + return Changed ? &I : 0; + } + + // XorSelf - Implements: X ^ X --> 0 + struct XorSelf { + Value *RHS; + XorSelf(Value *rhs) : RHS(rhs) {} + bool shouldApply(Value *LHS) const { return LHS == RHS; } + Instruction *apply(BinaryOperator &Xor) const { + return &Xor; + } + }; + + + Instruction *InstCombiner::visitXor(BinaryOperator &I) { + bool Changed = SimplifyCommutative(I); + Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); + + // xor X, X = 0, even if X is nested in a sequence of Xor's. + if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) { + assert(Result == &I && "AssociativeOpt didn't work?"); + return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); + } + + if (ConstantIntegral *RHS = dyn_cast(Op1)) { + // xor X, 0 == X + if (RHS->isNullValue()) + return ReplaceInstUsesWith(I, Op0); + + if (BinaryOperator *Op0I = dyn_cast(Op0)) { + // xor (setcc A, B), true = not (setcc A, B) = setncc A, B + if (SetCondInst *SCI = dyn_cast(Op0I)) + if (RHS == ConstantBool::True && SCI->hasOneUse()) + return new SetCondInst(SCI->getInverseCondition(), + SCI->getOperand(0), SCI->getOperand(1)); + + // ~(c-X) == X-c-1 == X+(-c-1) + if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue()) + if (Constant *Op0I0C = dyn_cast(Op0I->getOperand(0))) { + Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C); + Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C, + ConstantInt::get(I.getType(), 1)); + return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS); + } + + // ~(~X & Y) --> (X | ~Y) + if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) { + if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands(); + if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) { + Instruction *NotY = + BinaryOperator::createNot(Op0I->getOperand(1), + Op0I->getOperand(1)->getName()+".not"); + InsertNewInstBefore(NotY, I); + return BinaryOperator::createOr(Op0NotVal, NotY); + } + } + + if (ConstantInt *Op0CI = dyn_cast(Op0I->getOperand(1))) + switch (Op0I->getOpcode()) { + case Instruction::Add: + // ~(X-c) --> (-c-1)-X + if (RHS->isAllOnesValue()) { + Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI); + return BinaryOperator::createSub( + ConstantExpr::getSub(NegOp0CI, + ConstantInt::get(I.getType(), 1)), + Op0I->getOperand(0)); + } + break; + case Instruction::And: + // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0 + if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue()) + return BinaryOperator::createOr(Op0, RHS); + break; + case Instruction::Or: + // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 + if (ConstantExpr::getAnd(RHS, Op0CI) == RHS) + return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS)); + break; + default: break; + } + } + + // Try to fold constant and into select arguments. + if (SelectInst *SI = dyn_cast(Op0)) + if (Instruction *R = FoldBinOpIntoSelect(I, SI, this)) + return R; + if (isa(Op0)) + if (Instruction *NV = FoldOpIntoPhi(I)) + return NV; + } + + if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1 + if (X == Op1) + return ReplaceInstUsesWith(I, + ConstantIntegral::getAllOnesValue(I.getType())); + + if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1 + if (X == Op0) + return ReplaceInstUsesWith(I, + ConstantIntegral::getAllOnesValue(I.getType())); + + if (Instruction *Op1I = dyn_cast(Op1)) + if (Op1I->getOpcode() == Instruction::Or) { + if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B + cast(Op1I)->swapOperands(); + I.swapOperands(); + std::swap(Op0, Op1); + } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B + I.swapOperands(); + std::swap(Op0, Op1); + } + } else if (Op1I->getOpcode() == Instruction::Xor) { + if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B + return ReplaceInstUsesWith(I, Op1I->getOperand(1)); + else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B + return ReplaceInstUsesWith(I, Op1I->getOperand(0)); + } + + if (Instruction *Op0I = dyn_cast(Op0)) + if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) { + if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B + cast(Op0I)->swapOperands(); + if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B + Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1, + Op1->getName()+".not"), I); + return BinaryOperator::createAnd(Op0I->getOperand(0), NotB); + } + } else if (Op0I->getOpcode() == Instruction::Xor) { + if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B + return ReplaceInstUsesWith(I, Op0I->getOperand(1)); + else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B + return ReplaceInstUsesWith(I, Op0I->getOperand(0)); + } + + // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 + Value *A, *B; ConstantInt *C1, *C2; + if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) && + match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && + ConstantExpr::getAnd(C1, C2)->isNullValue()) + return BinaryOperator::createOr(Op0, Op1); + + // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B) + if (SetCondInst *RHS = dyn_cast(I.getOperand(1))) + if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS))) + return R; + + return Changed ? &I : 0; + } + + /// MulWithOverflow - Compute Result = In1*In2, returning true if the result + /// overflowed for this type. + static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1, + ConstantInt *In2) { + Result = cast(ConstantExpr::getMul(In1, In2)); + return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1; + } + + static bool isPositive(ConstantInt *C) { + return cast(C)->getValue() >= 0; + } + + /// AddWithOverflow - Compute Result = In1+In2, returning true if the result + /// overflowed for this type. + static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1, + ConstantInt *In2) { + Result = cast(ConstantExpr::getAdd(In1, In2)); + + if (In1->getType()->isUnsigned()) + return cast(Result)->getValue() < + cast(In1)->getValue(); + if (isPositive(In1) != isPositive(In2)) + return false; + if (isPositive(In1)) + return cast(Result)->getValue() < + cast(In1)->getValue(); + return cast(Result)->getValue() > + cast(In1)->getValue(); + } + + Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) { + bool Changed = SimplifyCommutative(I); + Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); + const Type *Ty = Op0->getType(); + + // setcc X, X + if (Op0 == Op1) + return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I))); + + // setcc , 0 - Global/Stack value addresses are never null! + if (isa(Op1) && + (isa(Op0) || isa(Op0))) + return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I))); + + + // setcc's with boolean values can always be turned into bitwise operations + if (Ty == Type::BoolTy) { + switch (I.getOpcode()) { + default: assert(0 && "Invalid setcc instruction!"); + case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B) + Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp"); + InsertNewInstBefore(Xor, I); + return BinaryOperator::createNot(Xor); + } + case Instruction::SetNE: + return BinaryOperator::createXor(Op0, Op1); + + case Instruction::SetGT: + std::swap(Op0, Op1); // Change setgt -> setlt + // FALL THROUGH + case Instruction::SetLT: { // setlt bool A, B -> ~X & Y + Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp"); + InsertNewInstBefore(Not, I); + return BinaryOperator::createAnd(Not, Op1); + } + case Instruction::SetGE: + std::swap(Op0, Op1); // Change setge -> setle + // FALL THROUGH + case Instruction::SetLE: { // setle bool %A, %B -> ~A | B + Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp"); + InsertNewInstBefore(Not, I); + return BinaryOperator::createOr(Not, Op1); + } + } + } + + // See if we are doing a comparison between a constant and an instruction that + // can be folded into the comparison. + if (ConstantInt *CI = dyn_cast(Op1)) { + // Check to see if we are comparing against the minimum or maximum value... + if (CI->isMinValue()) { + if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE + return ReplaceInstUsesWith(I, ConstantBool::False); + if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE + return ReplaceInstUsesWith(I, ConstantBool::True); + if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN + return BinaryOperator::createSetEQ(Op0, Op1); + if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN + return BinaryOperator::createSetNE(Op0, Op1); + + } else if (CI->isMaxValue()) { + if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE + return ReplaceInstUsesWith(I, ConstantBool::False); + if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE + return ReplaceInstUsesWith(I, ConstantBool::True); + if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX + return BinaryOperator::createSetEQ(Op0, Op1); + if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX + return BinaryOperator::createSetNE(Op0, Op1); + + // Comparing against a value really close to min or max? + } else if (isMinValuePlusOne(CI)) { + if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN + return BinaryOperator::createSetEQ(Op0, SubOne(CI)); + if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN + return BinaryOperator::createSetNE(Op0, SubOne(CI)); + + } else if (isMaxValueMinusOne(CI)) { + if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX + return BinaryOperator::createSetEQ(Op0, AddOne(CI)); + if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX + return BinaryOperator::createSetNE(Op0, AddOne(CI)); + } + + // If we still have a setle or setge instruction, turn it into the + // appropriate setlt or setgt instruction. Since the border cases have + // already been handled above, this requires little checking. + // + if (I.getOpcode() == Instruction::SetLE) + return BinaryOperator::createSetLT(Op0, AddOne(CI)); + if (I.getOpcode() == Instruction::SetGE) + return BinaryOperator::createSetGT(Op0, SubOne(CI)); + + if (Instruction *LHSI = dyn_cast(Op0)) + switch (LHSI->getOpcode()) { + case Instruction::PHI: + if (Instruction *NV = FoldOpIntoPhi(I)) + return NV; + break; + case Instruction::And: + if (LHSI->hasOneUse() && isa(LHSI->getOperand(1)) && + LHSI->getOperand(0)->hasOneUse()) { + // If this is: (X >> C1) & C2 != C3 (where any shift and any compare + // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This + // happens a LOT in code produced by the C front-end, for bitfield + // access. + ShiftInst *Shift = dyn_cast(LHSI->getOperand(0)); + ConstantUInt *ShAmt; + ShAmt = Shift ? dyn_cast(Shift->getOperand(1)) : 0; + ConstantInt *AndCST = cast(LHSI->getOperand(1)); + const Type *Ty = LHSI->getType(); + + // We can fold this as long as we can't shift unknown bits + // into the mask. This can only happen with signed shift + // rights, as they sign-extend. + if (ShAmt) { + bool CanFold = Shift->getOpcode() != Instruction::Shr || + Shift->getType()->isUnsigned(); + if (!CanFold) { + // To test for the bad case of the signed shr, see if any + // of the bits shifted in could be tested after the mask. + Constant *OShAmt = ConstantUInt::get(Type::UByteTy, + Ty->getPrimitiveSize()*8-ShAmt->getValue()); + Constant *ShVal = + ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt); + if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue()) + CanFold = true; + } + + if (CanFold) { + Constant *NewCst; + if (Shift->getOpcode() == Instruction::Shl) + NewCst = ConstantExpr::getUShr(CI, ShAmt); + else + NewCst = ConstantExpr::getShl(CI, ShAmt); + + // Check to see if we are shifting out any of the bits being + // compared. + if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){ + // If we shifted bits out, the fold is not going to work out. + // As a special case, check to see if this means that the + // result is always true or false now. + if (I.getOpcode() == Instruction::SetEQ) + return ReplaceInstUsesWith(I, ConstantBool::False); + if (I.getOpcode() == Instruction::SetNE) + return ReplaceInstUsesWith(I, ConstantBool::True); + } else { + I.setOperand(1, NewCst); + Constant *NewAndCST; + if (Shift->getOpcode() == Instruction::Shl) + NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt); + else + NewAndCST = ConstantExpr::getShl(AndCST, ShAmt); + LHSI->setOperand(1, NewAndCST); + LHSI->setOperand(0, Shift->getOperand(0)); + WorkList.push_back(Shift); // Shift is dead. + AddUsesToWorkList(I); + return &I; + } + } + } + } + break; + + case Instruction::Cast: { // (setcc (cast X to larger), CI) + const Type *SrcTy = LHSI->getOperand(0)->getType(); + if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) { + unsigned SrcBits = SrcTy->getPrimitiveSize()*8; + if (SrcTy == Type::BoolTy) SrcBits = 1; + unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8; + if (LHSI->getType() == Type::BoolTy) DestBits = 1; + if (SrcBits < DestBits) { + // Check to see if the comparison is always true or false. + Constant *NewCst = ConstantExpr::getCast(CI, SrcTy); + if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) { + Constant *Min = ConstantIntegral::getMinValue(SrcTy); + Constant *Max = ConstantIntegral::getMaxValue(SrcTy); + Min = ConstantExpr::getCast(Min, LHSI->getType()); + Max = ConstantExpr::getCast(Max, LHSI->getType()); + switch (I.getOpcode()) { + default: assert(0 && "unknown integer comparison"); + case Instruction::SetEQ: + return ReplaceInstUsesWith(I, ConstantBool::False); + case Instruction::SetNE: + return ReplaceInstUsesWith(I, ConstantBool::True); + case Instruction::SetLT: + return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI)); + case Instruction::SetGT: + return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI)); + } + } + + return new SetCondInst(I.getOpcode(), LHSI->getOperand(0), + ConstantExpr::getCast(CI, SrcTy)); + } + } + break; + } + case Instruction::Shl: // (setcc (shl X, ShAmt), CI) + if (ConstantUInt *ShAmt = dyn_cast(LHSI->getOperand(1))) { + switch (I.getOpcode()) { + default: break; + case Instruction::SetEQ: + case Instruction::SetNE: { + // If we are comparing against bits always shifted out, the + // comparison cannot succeed. + Constant *Comp = + ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt); + if (Comp != CI) {// Comparing against a bit that we know is zero. + bool IsSetNE = I.getOpcode() == Instruction::SetNE; + Constant *Cst = ConstantBool::get(IsSetNE); + return ReplaceInstUsesWith(I, Cst); + } + + if (LHSI->hasOneUse()) { + // Otherwise strength reduce the shift into an and. + unsigned ShAmtVal = ShAmt->getValue(); + unsigned TypeBits = CI->getType()->getPrimitiveSize()*8; + uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1; + + Constant *Mask; + if (CI->getType()->isUnsigned()) { + Mask = ConstantUInt::get(CI->getType(), Val); + } else if (ShAmtVal != 0) { + Mask = ConstantSInt::get(CI->getType(), Val); + } else { + Mask = ConstantInt::getAllOnesValue(CI->getType()); + } + + Instruction *AndI = + BinaryOperator::createAnd(LHSI->getOperand(0), + Mask, LHSI->getName()+".mask"); + Value *And = InsertNewInstBefore(AndI, I); + return new SetCondInst(I.getOpcode(), And, + ConstantExpr::getUShr(CI, ShAmt)); + } + } + } + } + break; + + case Instruction::Shr: // (setcc (shr X, ShAmt), CI) + if (ConstantUInt *ShAmt = dyn_cast(LHSI->getOperand(1))) { + switch (I.getOpcode()) { + default: break; + case Instruction::SetEQ: + case Instruction::SetNE: { + // If we are comparing against bits always shifted out, the + // comparison cannot succeed. + Constant *Comp = + ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt); + + if (Comp != CI) {// Comparing against a bit that we know is zero. + bool IsSetNE = I.getOpcode() == Instruction::SetNE; + Constant *Cst = ConstantBool::get(IsSetNE); + return ReplaceInstUsesWith(I, Cst); + } + + if (LHSI->hasOneUse() || CI->isNullValue()) { + unsigned ShAmtVal = ShAmt->getValue(); + + // Otherwise strength reduce the shift into an and. + uint64_t Val = ~0ULL; // All ones. + Val <<= ShAmtVal; // Shift over to the right spot. + + Constant *Mask; + if (CI->getType()->isUnsigned()) { + unsigned TypeBits = CI->getType()->getPrimitiveSize()*8; + Val &= (1ULL << TypeBits)-1; + Mask = ConstantUInt::get(CI->getType(), Val); + } else { + Mask = ConstantSInt::get(CI->getType(), Val); + } + + Instruction *AndI = + BinaryOperator::createAnd(LHSI->getOperand(0), + Mask, LHSI->getName()+".mask"); + Value *And = InsertNewInstBefore(AndI, I); + return new SetCondInst(I.getOpcode(), And, + ConstantExpr::getShl(CI, ShAmt)); + } + break; + } + } + } + break; + + case Instruction::Div: + // Fold: (div X, C1) op C2 -> range check + if (ConstantInt *DivRHS = dyn_cast(LHSI->getOperand(1))) { + // Fold this div into the comparison, producing a range check. + // Determine, based on the divide type, what the range is being + // checked. If there is an overflow on the low or high side, remember + // it, otherwise compute the range [low, hi) bounding the new value. + bool LoOverflow = false, HiOverflow = 0; + ConstantInt *LoBound = 0, *HiBound = 0; + + ConstantInt *Prod; + bool ProdOV = MulWithOverflow(Prod, CI, DivRHS); + + if (DivRHS->isNullValue()) { // Don't hack on divide by zeros. + } else if (LHSI->getType()->isUnsigned()) { // udiv + LoBound = Prod; + LoOverflow = ProdOV; + HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS); + } else if (isPositive(DivRHS)) { // Divisor is > 0. + if (CI->isNullValue()) { // (X / pos) op 0 + // Can't overflow. + LoBound = cast(ConstantExpr::getNeg(SubOne(DivRHS))); + HiBound = DivRHS; + } else if (isPositive(CI)) { // (X / pos) op pos + LoBound = Prod; + LoOverflow = ProdOV; + HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS); + } else { // (X / pos) op neg + Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS)); + LoOverflow = AddWithOverflow(LoBound, Prod, + cast(DivRHSH)); + HiBound = Prod; + HiOverflow = ProdOV; + } + } else { // Divisor is < 0. + if (CI->isNullValue()) { // (X / neg) op 0 + LoBound = AddOne(DivRHS); + HiBound = cast(ConstantExpr::getNeg(DivRHS)); + } else if (isPositive(CI)) { // (X / neg) op pos + HiOverflow = LoOverflow = ProdOV; + if (!LoOverflow) + LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS)); + HiBound = AddOne(Prod); + } else { // (X / neg) op neg + LoBound = Prod; + LoOverflow = HiOverflow = ProdOV; + HiBound = cast(ConstantExpr::getSub(Prod, DivRHS)); + } + } + + if (LoBound) { + Value *X = LHSI->getOperand(0); + switch (I.getOpcode()) { + default: assert(0 && "Unhandled setcc opcode!"); + case Instruction::SetEQ: + if (LoOverflow && HiOverflow) + return ReplaceInstUsesWith(I, ConstantBool::False); + else if (HiOverflow) + return new SetCondInst(Instruction::SetGE, X, LoBound); + else if (LoOverflow) + return new SetCondInst(Instruction::SetLT, X, HiBound); + else + return InsertRangeTest(X, LoBound, HiBound, true, I); + case Instruction::SetNE: + if (LoOverflow && HiOverflow) + return ReplaceInstUsesWith(I, ConstantBool::True); + else if (HiOverflow) + return new SetCondInst(Instruction::SetLT, X, LoBound); + else if (LoOverflow) + return new SetCondInst(Instruction::SetGE, X, HiBound); + else + return InsertRangeTest(X, LoBound, HiBound, false, I); + case Instruction::SetLT: + if (LoOverflow) + return ReplaceInstUsesWith(I, ConstantBool::False); + return new SetCondInst(Instruction::SetLT, X, LoBound); + case Instruction::SetGT: + if (HiOverflow) + return ReplaceInstUsesWith(I, ConstantBool::False); + return new SetCondInst(Instruction::SetGE, X, HiBound); + } + } + } + break; + case Instruction::Select: + // If either operand of the select is a constant, we can fold the + // comparison into the select arms, which will cause one to be + // constant folded and the select turned into a bitwise or. + Value *Op1 = 0, *Op2 = 0; + if (LHSI->hasOneUse()) { + if (Constant *C = dyn_cast(LHSI->getOperand(1))) { + // Fold the known value into the constant operand. + Op1 = ConstantExpr::get(I.getOpcode(), C, CI); + // Insert a new SetCC of the other select operand. + Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(), + LHSI->getOperand(2), CI, + I.getName()), I); + } else if (Constant *C = dyn_cast(LHSI->getOperand(2))) { + // Fold the known value into the constant operand. + Op2 = ConstantExpr::get(I.getOpcode(), C, CI); + // Insert a new SetCC of the other select operand. + Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(), + LHSI->getOperand(1), CI, + I.getName()), I); + } + } + + if (Op1) + return new SelectInst(LHSI->getOperand(0), Op1, Op2); + break; + } + + // Simplify seteq and setne instructions... + if (I.getOpcode() == Instruction::SetEQ || + I.getOpcode() == Instruction::SetNE) { + bool isSetNE = I.getOpcode() == Instruction::SetNE; + + // If the first operand is (and|or|xor) with a constant, and the second + // operand is a constant, simplify a bit. + if (BinaryOperator *BO = dyn_cast(Op0)) { + switch (BO->getOpcode()) { + case Instruction::Rem: + // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one. + if (CI->isNullValue() && isa(BO->getOperand(1)) && + BO->hasOneUse() && + cast(BO->getOperand(1))->getValue() > 1) + if (unsigned L2 = + Log2(cast(BO->getOperand(1))->getValue())) { + const Type *UTy = BO->getType()->getUnsignedVersion(); + Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0), + UTy, "tmp"), I); + Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2); + Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX, + RHSCst, BO->getName()), I); + return BinaryOperator::create(I.getOpcode(), NewRem, + Constant::getNullValue(UTy)); + } + break; + + case Instruction::Add: + // Replace ((add A, B) != C) with (A != C-B) if B & C are constants. + if (ConstantInt *BOp1C = dyn_cast(BO->getOperand(1))) { + if (BO->hasOneUse()) + return new SetCondInst(I.getOpcode(), BO->getOperand(0), + ConstantExpr::getSub(CI, BOp1C)); + } else if (CI->isNullValue()) { + // Replace ((add A, B) != 0) with (A != -B) if A or B is + // efficiently invertible, or if the add has just this one use. + Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1); + + if (Value *NegVal = dyn_castNegVal(BOp1)) + return new SetCondInst(I.getOpcode(), BOp0, NegVal); + else if (Value *NegVal = dyn_castNegVal(BOp0)) + return new SetCondInst(I.getOpcode(), NegVal, BOp1); + else if (BO->hasOneUse()) { + Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName()); + BO->setName(""); + InsertNewInstBefore(Neg, I); + return new SetCondInst(I.getOpcode(), BOp0, Neg); + } + } + break; + case Instruction::Xor: + // For the xor case, we can xor two constants together, eliminating + // the explicit xor. + if (Constant *BOC = dyn_cast(BO->getOperand(1))) + return BinaryOperator::create(I.getOpcode(), BO->getOperand(0), + ConstantExpr::getXor(CI, BOC)); + + // FALLTHROUGH + case Instruction::Sub: + // Replace (([sub|xor] A, B) != 0) with (A != B) + if (CI->isNullValue()) + return new SetCondInst(I.getOpcode(), BO->getOperand(0), + BO->getOperand(1)); + break; + + case Instruction::Or: + // If bits are being or'd in that are not present in the constant we + // are comparing against, then the comparison could never succeed! + if (Constant *BOC = dyn_cast(BO->getOperand(1))) { + Constant *NotCI = ConstantExpr::getNot(CI); + if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue()) + return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE)); + } + break; + + case Instruction::And: + if (ConstantInt *BOC = dyn_cast(BO->getOperand(1))) { + // If bits are being compared against that are and'd out, then the + // comparison can never succeed! + if (!ConstantExpr::getAnd(CI, + ConstantExpr::getNot(BOC))->isNullValue()) + return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE)); + + // If we have ((X & C) == C), turn it into ((X & C) != 0). + if (CI == BOC && isOneBitSet(CI)) + return new SetCondInst(isSetNE ? Instruction::SetEQ : + Instruction::SetNE, Op0, + Constant::getNullValue(CI->getType())); + + // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X + // to be a signed value as appropriate. + if (isSignBit(BOC)) { + Value *X = BO->getOperand(0); + // If 'X' is not signed, insert a cast now... + if (!BOC->getType()->isSigned()) { + const Type *DestTy = BOC->getType()->getSignedVersion(); + X = InsertCastBefore(X, DestTy, I); + } + return new SetCondInst(isSetNE ? Instruction::SetLT : + Instruction::SetGE, X, + Constant::getNullValue(X->getType())); + } + + // ((X & ~7) == 0) --> X < 8 + if (CI->isNullValue() && isHighOnes(BOC)) { + Value *X = BO->getOperand(0); + Constant *NegX = ConstantExpr::getNeg(BOC); + + // If 'X' is signed, insert a cast now. + if (NegX->getType()->isSigned()) { + const Type *DestTy = NegX->getType()->getUnsignedVersion(); + X = InsertCastBefore(X, DestTy, I); + NegX = ConstantExpr::getCast(NegX, DestTy); + } + + return new SetCondInst(isSetNE ? Instruction::SetGE : + Instruction::SetLT, X, NegX); + } + + } + default: break; + } + } + } else { // Not a SetEQ/SetNE + // If the LHS is a cast from an integral value of the same size, + if (CastInst *Cast = dyn_cast(Op0)) { + Value *CastOp = Cast->getOperand(0); + const Type *SrcTy = CastOp->getType(); + unsigned SrcTySize = SrcTy->getPrimitiveSize(); + if (SrcTy != Cast->getType() && SrcTy->isInteger() && + SrcTySize == Cast->getType()->getPrimitiveSize()) { + assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) && + "Source and destination signednesses should differ!"); + if (Cast->getType()->isSigned()) { + // If this is a signed comparison, check for comparisons in the + // vicinity of zero. + if (I.getOpcode() == Instruction::SetLT && CI->isNullValue()) + // X < 0 => x > 127 + return BinaryOperator::createSetGT(CastOp, + ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1)); + else if (I.getOpcode() == Instruction::SetGT && + cast(CI)->getValue() == -1) + // X > -1 => x < 128 + return BinaryOperator::createSetLT(CastOp, + ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1))); + } else { + ConstantUInt *CUI = cast(CI); + if (I.getOpcode() == Instruction::SetLT && + CUI->getValue() == 1ULL << (SrcTySize*8-1)) + // X < 128 => X > -1 + return BinaryOperator::createSetGT(CastOp, + ConstantSInt::get(SrcTy, -1)); + else if (I.getOpcode() == Instruction::SetGT && + CUI->getValue() == (1ULL << (SrcTySize*8-1))-1) + // X > 127 => X < 0 + return BinaryOperator::createSetLT(CastOp, + Constant::getNullValue(SrcTy)); + } + } + } + } + } + + // Test to see if the operands of the setcc are casted versions of other + // values. If the cast can be stripped off both arguments, we do so now. + if (CastInst *CI = dyn_cast(Op0)) { + Value *CastOp0 = CI->getOperand(0); + if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) && + (isa(Op1) || isa(Op1)) && + (I.getOpcode() == Instruction::SetEQ || + I.getOpcode() == Instruction::SetNE)) { + // We keep moving the cast from the left operand over to the right + // operand, where it can often be eliminated completely. + Op0 = CastOp0; + + // If operand #1 is a cast instruction, see if we can eliminate it as + // well. + if (CastInst *CI2 = dyn_cast(Op1)) + if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo( + Op0->getType())) + Op1 = CI2->getOperand(0); + + // If Op1 is a constant, we can fold the cast into the constant. + if (Op1->getType() != Op0->getType()) + if (Constant *Op1C = dyn_cast(Op1)) { + Op1 = ConstantExpr::getCast(Op1C, Op0->getType()); + } else { + // Otherwise, cast the RHS right before the setcc + Op1 = new CastInst(Op1, Op0->getType(), Op1->getName()); + InsertNewInstBefore(cast(Op1), I); + } + return BinaryOperator::create(I.getOpcode(), Op0, Op1); + } + + // Handle the special case of: setcc (cast bool to X), + // This comes up when you have code like + // int X = A < B; + // if (X) ... + // For generality, we handle any zero-extension of any operand comparison + // with a constant. + if (ConstantInt *ConstantRHS = dyn_cast(Op1)) { + const Type *SrcTy = CastOp0->getType(); + const Type *DestTy = Op0->getType(); + if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() && + (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) { + // Ok, we have an expansion of operand 0 into a new type. Get the + // constant value, masink off bits which are not set in the RHS. These + // could be set if the destination value is signed. + uint64_t ConstVal = ConstantRHS->getRawValue(); + ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1; + + // If the constant we are comparing it with has high bits set, which + // don't exist in the original value, the values could never be equal, + // because the source would be zero extended. + unsigned SrcBits = + SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8; + bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1)); + if (ConstVal & ~((1ULL << SrcBits)-1)) { + switch (I.getOpcode()) { + default: assert(0 && "Unknown comparison type!"); + case Instruction::SetEQ: + return ReplaceInstUsesWith(I, ConstantBool::False); + case Instruction::SetNE: + return ReplaceInstUsesWith(I, ConstantBool::True); + case Instruction::SetLT: + case Instruction::SetLE: + if (DestTy->isSigned() && HasSignBit) + return ReplaceInstUsesWith(I, ConstantBool::False); + return ReplaceInstUsesWith(I, ConstantBool::True); + case Instruction::SetGT: + case Instruction::SetGE: + if (DestTy->isSigned() && HasSignBit) + return ReplaceInstUsesWith(I, ConstantBool::True); + return ReplaceInstUsesWith(I, ConstantBool::False); + } + } + + // Otherwise, we can replace the setcc with a setcc of the smaller + // operand value. + Op1 = ConstantExpr::getCast(cast(Op1), SrcTy); + return BinaryOperator::create(I.getOpcode(), CastOp0, Op1); + } + } + } + return Changed ? &I : 0; + } + + + + Instruction *InstCombiner::visitShiftInst(ShiftInst &I) { + assert(I.getOperand(1)->getType() == Type::UByteTy); + Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); + bool isLeftShift = I.getOpcode() == Instruction::Shl; + + // shl X, 0 == X and shr X, 0 == X + // shl 0, X == 0 and shr 0, X == 0 + if (Op1 == Constant::getNullValue(Type::UByteTy) || + Op0 == Constant::getNullValue(Op0->getType())) + return ReplaceInstUsesWith(I, Op0); + + // shr int -1, X = -1 (for any arithmetic shift rights of ~0) + if (!isLeftShift) + if (ConstantSInt *CSI = dyn_cast(Op0)) + if (CSI->isAllOnesValue()) + return ReplaceInstUsesWith(I, CSI); + + // Try to fold constant and into select arguments. + if (isa(Op0)) + if (SelectInst *SI = dyn_cast(Op1)) + if (Instruction *R = FoldBinOpIntoSelect(I, SI, this)) + return R; + + if (ConstantUInt *CUI = dyn_cast(Op1)) { + // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr + // of a signed value. + // + unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8; + if (CUI->getValue() >= TypeBits) { + if (!Op0->getType()->isSigned() || isLeftShift) + return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType())); + else { + I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1)); + return &I; + } + } + + // ((X*C1) << C2) == (X * (C1 << C2)) + if (BinaryOperator *BO = dyn_cast(Op0)) + if (BO->getOpcode() == Instruction::Mul && isLeftShift) + if (Constant *BOOp = dyn_cast(BO->getOperand(1))) + return BinaryOperator::createMul(BO->getOperand(0), + ConstantExpr::getShl(BOOp, CUI)); + + // Try to fold constant and into select arguments. + if (SelectInst *SI = dyn_cast(Op0)) + if (Instruction *R = FoldBinOpIntoSelect(I, SI, this)) + return R; + if (isa(Op0)) + if (Instruction *NV = FoldOpIntoPhi(I)) + return NV; + + // If the operand is an bitwise operator with a constant RHS, and the + // shift is the only use, we can pull it out of the shift. + if (Op0->hasOneUse()) + if (BinaryOperator *Op0BO = dyn_cast(Op0)) + if (ConstantInt *Op0C = dyn_cast(Op0BO->getOperand(1))) { + bool isValid = true; // Valid only for And, Or, Xor + bool highBitSet = false; // Transform if high bit of constant set? + + switch (Op0BO->getOpcode()) { + default: isValid = false; break; // Do not perform transform! + case Instruction::Or: + case Instruction::Xor: + highBitSet = false; + break; + case Instruction::And: + highBitSet = true; + break; + } + + // If this is a signed shift right, and the high bit is modified + // by the logical operation, do not perform the transformation. + // The highBitSet boolean indicates the value of the high bit of + // the constant which would cause it to be modified for this + // operation. + // + if (isValid && !isLeftShift && !I.getType()->isUnsigned()) { + uint64_t Val = Op0C->getRawValue(); + isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet; + } + + if (isValid) { + Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI); + + Instruction *NewShift = + new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI, + Op0BO->getName()); + Op0BO->setName(""); + InsertNewInstBefore(NewShift, I); + + return BinaryOperator::create(Op0BO->getOpcode(), NewShift, + NewRHS); + } + } + + // If this is a shift of a shift, see if we can fold the two together... + if (ShiftInst *Op0SI = dyn_cast(Op0)) + if (ConstantUInt *ShiftAmt1C = + dyn_cast(Op0SI->getOperand(1))) { + unsigned ShiftAmt1 = ShiftAmt1C->getValue(); + unsigned ShiftAmt2 = CUI->getValue(); + + // Check for (A << c1) << c2 and (A >> c1) >> c2 + if (I.getOpcode() == Op0SI->getOpcode()) { + unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift... + if (Op0->getType()->getPrimitiveSize()*8 < Amt) + Amt = Op0->getType()->getPrimitiveSize()*8; + return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0), + ConstantUInt::get(Type::UByteTy, Amt)); + } + + // Check for (A << c1) >> c2 or visaversa. If we are dealing with + // signed types, we can only support the (A >> c1) << c2 configuration, + // because it can not turn an arbitrary bit of A into a sign bit. + if (I.getType()->isUnsigned() || isLeftShift) { + // Calculate bitmask for what gets shifted off the edge... + Constant *C = ConstantIntegral::getAllOnesValue(I.getType()); + if (isLeftShift) + C = ConstantExpr::getShl(C, ShiftAmt1C); + else + C = ConstantExpr::getShr(C, ShiftAmt1C); + + Instruction *Mask = + BinaryOperator::createAnd(Op0SI->getOperand(0), C, + Op0SI->getOperand(0)->getName()+".mask"); + InsertNewInstBefore(Mask, I); + + // Figure out what flavor of shift we should use... + if (ShiftAmt1 == ShiftAmt2) + return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2 + else if (ShiftAmt1 < ShiftAmt2) { + return new ShiftInst(I.getOpcode(), Mask, + ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1)); + } else { + return new ShiftInst(Op0SI->getOpcode(), Mask, + ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2)); + } + } + } + } + + return 0; + } + + enum CastType { + Noop = 0, + Truncate = 1, + Signext = 2, + Zeroext = 3 + }; + + /// getCastType - In the future, we will split the cast instruction into these + /// various types. Until then, we have to do the analysis here. + static CastType getCastType(const Type *Src, const Type *Dest) { + assert(Src->isIntegral() && Dest->isIntegral() && + "Only works on integral types!"); + unsigned SrcSize = Src->getPrimitiveSize()*8; + if (Src == Type::BoolTy) SrcSize = 1; + unsigned DestSize = Dest->getPrimitiveSize()*8; + if (Dest == Type::BoolTy) DestSize = 1; + + if (SrcSize == DestSize) return Noop; + if (SrcSize > DestSize) return Truncate; + if (Src->isSigned()) return Signext; + return Zeroext; + } + + + // isEliminableCastOfCast - Return true if it is valid to eliminate the CI + // instruction. + // + static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy, + const Type *DstTy, TargetData *TD) { + + // It is legal to eliminate the instruction if casting A->B->A if the sizes + // are identical and the bits don't get reinterpreted (for example + // int->float->int would not be allowed). + if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy)) + return true; + + // If we are casting between pointer and integer types, treat pointers as + // integers of the appropriate size for the code below. + if (isa(SrcTy)) SrcTy = TD->getIntPtrType(); + if (isa(MidTy)) MidTy = TD->getIntPtrType(); + if (isa(DstTy)) DstTy = TD->getIntPtrType(); + + // Allow free casting and conversion of sizes as long as the sign doesn't + // change... + if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) { + CastType FirstCast = getCastType(SrcTy, MidTy); + CastType SecondCast = getCastType(MidTy, DstTy); + + // Capture the effect of these two casts. If the result is a legal cast, + // the CastType is stored here, otherwise a special code is used. + static const unsigned CastResult[] = { + // First cast is noop + 0, 1, 2, 3, + // First cast is a truncate + 1, 1, 4, 4, // trunc->extend is not safe to eliminate + // First cast is a sign ext + 2, 5, 2, 4, // signext->zeroext never ok + // First cast is a zero ext + 3, 5, 3, 3, + }; + + unsigned Result = CastResult[FirstCast*4+SecondCast]; + switch (Result) { + default: assert(0 && "Illegal table value!"); + case 0: + case 1: + case 2: + case 3: + // FIXME: in the future, when LLVM has explicit sign/zeroextends and + // truncates, we could eliminate more casts. + return (unsigned)getCastType(SrcTy, DstTy) == Result; + case 4: + return false; // Not possible to eliminate this here. + case 5: + // Sign or zero extend followed by truncate is always ok if the result + // is a truncate or noop. + CastType ResultCast = getCastType(SrcTy, DstTy); + if (ResultCast == Noop || ResultCast == Truncate) + return true; + // Otherwise we are still growing the value, we are only safe if the + // result will match the sign/zeroextendness of the result. + return ResultCast == FirstCast; + } + } + return false; + } + + static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) { + if (V->getType() == Ty || isa(V)) return false; + if (const CastInst *CI = dyn_cast(V)) + if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty, + TD)) + return false; + return true; + } + + /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the + /// InsertBefore instruction. This is specialized a bit to avoid inserting + /// casts that are known to not do anything... + /// + Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy, + Instruction *InsertBefore) { + if (V->getType() == DestTy) return V; + if (Constant *C = dyn_cast(V)) + return ConstantExpr::getCast(C, DestTy); + + CastInst *CI = new CastInst(V, DestTy, V->getName()); + InsertNewInstBefore(CI, *InsertBefore); + return CI; + } + + // CastInst simplification + // + Instruction *InstCombiner::visitCastInst(CastInst &CI) { + Value *Src = CI.getOperand(0); + + // If the user is casting a value to the same type, eliminate this cast + // instruction... + if (CI.getType() == Src->getType()) + return ReplaceInstUsesWith(CI, Src); + + // If casting the result of another cast instruction, try to eliminate this + // one! + // + if (CastInst *CSrc = dyn_cast(Src)) { + if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(), + CSrc->getType(), CI.getType(), TD)) { + // This instruction now refers directly to the cast's src operand. This + // has a good chance of making CSrc dead. + CI.setOperand(0, CSrc->getOperand(0)); + return &CI; + } + + // If this is an A->B->A cast, and we are dealing with integral types, try + // to convert this into a logical 'and' instruction. + // + if (CSrc->getOperand(0)->getType() == CI.getType() && + CI.getType()->isInteger() && CSrc->getType()->isInteger() && + CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() && + CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){ + assert(CSrc->getType() != Type::ULongTy && + "Cannot have type bigger than ulong!"); + uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1; + Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue); + return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp); + } + } + + // If this is a cast to bool, turn it into the appropriate setne instruction. + if (CI.getType() == Type::BoolTy) + return BinaryOperator::createSetNE(CI.getOperand(0), + Constant::getNullValue(CI.getOperand(0)->getType())); + + // If casting the result of a getelementptr instruction with no offset, turn + // this into a cast of the original pointer! + // + if (GetElementPtrInst *GEP = dyn_cast(Src)) { + bool AllZeroOperands = true; + for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i) + if (!isa(GEP->getOperand(i)) || + !cast(GEP->getOperand(i))->isNullValue()) { + AllZeroOperands = false; + break; + } + if (AllZeroOperands) { + CI.setOperand(0, GEP->getOperand(0)); + return &CI; + } + } + + // If we are casting a malloc or alloca to a pointer to a type of the same + // size, rewrite the allocation instruction to allocate the "right" type. + // + if (AllocationInst *AI = dyn_cast(Src)) + if (AI->hasOneUse() && !AI->isArrayAllocation()) + if (const PointerType *PTy = dyn_cast(CI.getType())) { + // Get the type really allocated and the type casted to... + const Type *AllocElTy = AI->getAllocatedType(); + const Type *CastElTy = PTy->getElementType(); + if (AllocElTy->isSized() && CastElTy->isSized()) { + unsigned AllocElTySize = TD->getTypeSize(AllocElTy); + unsigned CastElTySize = TD->getTypeSize(CastElTy); + + // If the allocation is for an even multiple of the cast type size + if (CastElTySize && (AllocElTySize % CastElTySize == 0)) { + Value *Amt = ConstantUInt::get(Type::UIntTy, + AllocElTySize/CastElTySize); + std::string Name = AI->getName(); AI->setName(""); + AllocationInst *New; + if (isa(AI)) + New = new MallocInst(CastElTy, Amt, Name); + else + New = new AllocaInst(CastElTy, Amt, Name); + InsertNewInstBefore(New, *AI); + return ReplaceInstUsesWith(CI, New); + } + } + } + + if (isa(Src)) + if (Instruction *NV = FoldOpIntoPhi(CI)) + return NV; + + // If the source value is an instruction with only this use, we can attempt to + // propagate the cast into the instruction. Also, only handle integral types + // for now. + if (Instruction *SrcI = dyn_cast(Src)) + if (SrcI->hasOneUse() && Src->getType()->isIntegral() && + CI.getType()->isInteger()) { // Don't mess with casts to bool here + const Type *DestTy = CI.getType(); + unsigned SrcBitSize = getTypeSizeInBits(Src->getType()); + unsigned DestBitSize = getTypeSizeInBits(DestTy); + + Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0; + Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0; + + switch (SrcI->getOpcode()) { + case Instruction::Add: + case Instruction::Mul: + case Instruction::And: + case Instruction::Or: + case Instruction::Xor: + // If we are discarding information, or just changing the sign, rewrite. + if (DestBitSize <= SrcBitSize && DestBitSize != 1) { + // Don't insert two casts if they cannot be eliminated. We allow two + // casts to be inserted if the sizes are the same. This could only be + // converting signedness, which is a noop. + if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) || + !ValueRequiresCast(Op0, DestTy, TD)) { + Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI); + Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI); + return BinaryOperator::create(cast(SrcI) + ->getOpcode(), Op0c, Op1c); + } + } + break; + case Instruction::Shl: + // Allow changing the sign of the source operand. Do not allow changing + // the size of the shift, UNLESS the shift amount is a constant. We + // mush not change variable sized shifts to a smaller size, because it + // is undefined to shift more bits out than exist in the value. + if (DestBitSize == SrcBitSize || + (DestBitSize < SrcBitSize && isa(Op1))) { + Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI); + return new ShiftInst(Instruction::Shl, Op0c, Op1); + } + break; + } + } + + return 0; + } + + /// GetSelectFoldableOperands - We want to turn code that looks like this: + /// %C = or %A, %B + /// %D = select %cond, %C, %A + /// into: + /// %C = select %cond, %B, 0 + /// %D = or %A, %C + /// + /// Assuming that the specified instruction is an operand to the select, return + /// a bitmask indicating which operands of this instruction are foldable if they + /// equal the other incoming value of the select. + /// + static unsigned GetSelectFoldableOperands(Instruction *I) { + switch (I->getOpcode()) { + case Instruction::Add: + case Instruction::Mul: + case Instruction::And: + case Instruction::Or: + case Instruction::Xor: + return 3; // Can fold through either operand. + case Instruction::Sub: // Can only fold on the amount subtracted. + case Instruction::Shl: // Can only fold on the shift amount. + case Instruction::Shr: + return 1; + default: + return 0; // Cannot fold + } + } + + /// GetSelectFoldableConstant - For the same transformation as the previous + /// function, return the identity constant that goes into the select. + static Constant *GetSelectFoldableConstant(Instruction *I) { + switch (I->getOpcode()) { + default: assert(0 && "This cannot happen!"); abort(); + case Instruction::Add: + case Instruction::Sub: + case Instruction::Or: + case Instruction::Xor: + return Constant::getNullValue(I->getType()); + case Instruction::Shl: + case Instruction::Shr: + return Constant::getNullValue(Type::UByteTy); + case Instruction::And: + return ConstantInt::getAllOnesValue(I->getType()); + case Instruction::Mul: + return ConstantInt::get(I->getType(), 1); + } + } + + Instruction *InstCombiner::visitSelectInst(SelectInst &SI) { + Value *CondVal = SI.getCondition(); + Value *TrueVal = SI.getTrueValue(); + Value *FalseVal = SI.getFalseValue(); + + // select true, X, Y -> X + // select false, X, Y -> Y + if (ConstantBool *C = dyn_cast(CondVal)) + if (C == ConstantBool::True) + return ReplaceInstUsesWith(SI, TrueVal); + else { + assert(C == ConstantBool::False); + return ReplaceInstUsesWith(SI, FalseVal); + } + + // select C, X, X -> X + if (TrueVal == FalseVal) + return ReplaceInstUsesWith(SI, TrueVal); + + if (SI.getType() == Type::BoolTy) + if (ConstantBool *C = dyn_cast(TrueVal)) { + if (C == ConstantBool::True) { + // Change: A = select B, true, C --> A = or B, C + return BinaryOperator::createOr(CondVal, FalseVal); + } else { + // Change: A = select B, false, C --> A = and !B, C + Value *NotCond = + InsertNewInstBefore(BinaryOperator::createNot(CondVal, + "not."+CondVal->getName()), SI); + return BinaryOperator::createAnd(NotCond, FalseVal); + } + } else if (ConstantBool *C = dyn_cast(FalseVal)) { + if (C == ConstantBool::False) { + // Change: A = select B, C, false --> A = and B, C + return BinaryOperator::createAnd(CondVal, TrueVal); + } else { + // Change: A = select B, C, true --> A = or !B, C + Value *NotCond = + InsertNewInstBefore(BinaryOperator::createNot(CondVal, + "not."+CondVal->getName()), SI); + return BinaryOperator::createOr(NotCond, TrueVal); + } + } + + // Selecting between two integer constants? + if (ConstantInt *TrueValC = dyn_cast(TrueVal)) + if (ConstantInt *FalseValC = dyn_cast(FalseVal)) { + // select C, 1, 0 -> cast C to int + if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) { + return new CastInst(CondVal, SI.getType()); + } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) { + // select C, 0, 1 -> cast !C to int + Value *NotCond = + InsertNewInstBefore(BinaryOperator::createNot(CondVal, + "not."+CondVal->getName()), SI); + return new CastInst(NotCond, SI.getType()); + } + + // If one of the constants is zero (we know they can't both be) and we + // have a setcc instruction with zero, and we have an 'and' with the + // non-constant value, eliminate this whole mess. This corresponds to + // cases like this: ((X & 27) ? 27 : 0) + if (TrueValC->isNullValue() || FalseValC->isNullValue()) + if (Instruction *IC = dyn_cast(SI.getCondition())) + if ((IC->getOpcode() == Instruction::SetEQ || + IC->getOpcode() == Instruction::SetNE) && + isa(IC->getOperand(1)) && + cast(IC->getOperand(1))->isNullValue()) + if (Instruction *ICA = dyn_cast(IC->getOperand(0))) + if (ICA->getOpcode() == Instruction::And && + isa(ICA->getOperand(1)) && + (ICA->getOperand(1) == TrueValC || + ICA->getOperand(1) == FalseValC) && + isOneBitSet(cast(ICA->getOperand(1)))) { + // Okay, now we know that everything is set up, we just don't + // know whether we have a setne or seteq and whether the true or + // false val is the zero. + bool ShouldNotVal = !TrueValC->isNullValue(); + ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE; + Value *V = ICA; + if (ShouldNotVal) + V = InsertNewInstBefore(BinaryOperator::create( + Instruction::Xor, V, ICA->getOperand(1)), SI); + return ReplaceInstUsesWith(SI, V); + } + } + + // See if we are selecting two values based on a comparison of the two values. + if (SetCondInst *SCI = dyn_cast(CondVal)) { + if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) { + // Transform (X == Y) ? X : Y -> Y + if (SCI->getOpcode() == Instruction::SetEQ) + return ReplaceInstUsesWith(SI, FalseVal); + // Transform (X != Y) ? X : Y -> X + if (SCI->getOpcode() == Instruction::SetNE) + return ReplaceInstUsesWith(SI, TrueVal); + // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc. + + } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){ + // Transform (X == Y) ? Y : X -> X + if (SCI->getOpcode() == Instruction::SetEQ) + return ReplaceInstUsesWith(SI, FalseVal); + // Transform (X != Y) ? Y : X -> Y + if (SCI->getOpcode() == Instruction::SetNE) + return ReplaceInstUsesWith(SI, TrueVal); + // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc. + } + } + + // See if we can fold the select into one of our operands. + if (SI.getType()->isInteger()) { + // See the comment above GetSelectFoldableOperands for a description of the + // transformation we are doing here. + if (Instruction *TVI = dyn_cast(TrueVal)) + if (TVI->hasOneUse() && TVI->getNumOperands() == 2 && + !isa(FalseVal)) + if (unsigned SFO = GetSelectFoldableOperands(TVI)) { + unsigned OpToFold = 0; + if ((SFO & 1) && FalseVal == TVI->getOperand(0)) { + OpToFold = 1; + } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) { + OpToFold = 2; + } + + if (OpToFold) { + Constant *C = GetSelectFoldableConstant(TVI); + std::string Name = TVI->getName(); TVI->setName(""); + Instruction *NewSel = + new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C, + Name); + InsertNewInstBefore(NewSel, SI); + if (BinaryOperator *BO = dyn_cast(TVI)) + return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel); + else if (ShiftInst *SI = dyn_cast(TVI)) + return new ShiftInst(SI->getOpcode(), FalseVal, NewSel); + else { + assert(0 && "Unknown instruction!!"); + } + } + } + + if (Instruction *FVI = dyn_cast(FalseVal)) + if (FVI->hasOneUse() && FVI->getNumOperands() == 2 && + !isa(TrueVal)) + if (unsigned SFO = GetSelectFoldableOperands(FVI)) { + unsigned OpToFold = 0; + if ((SFO & 1) && TrueVal == FVI->getOperand(0)) { + OpToFold = 1; + } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) { + OpToFold = 2; + } + + if (OpToFold) { + Constant *C = GetSelectFoldableConstant(FVI); + std::string Name = FVI->getName(); FVI->setName(""); + Instruction *NewSel = + new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold), + Name); + InsertNewInstBefore(NewSel, SI); + if (BinaryOperator *BO = dyn_cast(FVI)) + return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel); + else if (ShiftInst *SI = dyn_cast(FVI)) + return new ShiftInst(SI->getOpcode(), TrueVal, NewSel); + else { + assert(0 && "Unknown instruction!!"); + } + } + } + } + return 0; + } + + + // CallInst simplification + // + Instruction *InstCombiner::visitCallInst(CallInst &CI) { + // Intrinsics cannot occur in an invoke, so handle them here instead of in + // visitCallSite. + if (Function *F = CI.getCalledFunction()) + switch (F->getIntrinsicID()) { + case Intrinsic::memmove: + case Intrinsic::memcpy: + case Intrinsic::memset: + // memmove/cpy/set of zero bytes is a noop. + if (Constant *NumBytes = dyn_cast(CI.getOperand(3))) { + if (NumBytes->isNullValue()) + return EraseInstFromFunction(CI); + } + break; + default: + break; + } + + return visitCallSite(&CI); + } + + // InvokeInst simplification + // + Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) { + return visitCallSite(&II); + } + + // visitCallSite - Improvements for call and invoke instructions. + // + Instruction *InstCombiner::visitCallSite(CallSite CS) { + bool Changed = false; + + // If the callee is a constexpr cast of a function, attempt to move the cast + // to the arguments of the call/invoke. + if (transformConstExprCastCall(CS)) return 0; + + Value *Callee = CS.getCalledValue(); + const PointerType *PTy = cast(Callee->getType()); + const FunctionType *FTy = cast(PTy->getElementType()); + if (FTy->isVarArg()) { + // See if we can optimize any arguments passed through the varargs area of + // the call. + for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(), + E = CS.arg_end(); I != E; ++I) + if (CastInst *CI = dyn_cast(*I)) { + // If this cast does not effect the value passed through the varargs + // area, we can eliminate the use of the cast. + Value *Op = CI->getOperand(0); + if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) { + *I = Op; + Changed = true; + } + } + } + + return Changed ? CS.getInstruction() : 0; + } + + // transformConstExprCastCall - If the callee is a constexpr cast of a function, + // attempt to move the cast to the arguments of the call/invoke. + // + bool InstCombiner::transformConstExprCastCall(CallSite CS) { + if (!isa(CS.getCalledValue())) return false; + ConstantExpr *CE = cast(CS.getCalledValue()); + if (CE->getOpcode() != Instruction::Cast || !isa(CE->getOperand(0))) + return false; + Function *Callee = cast(CE->getOperand(0)); + Instruction *Caller = CS.getInstruction(); + + // Okay, this is a cast from a function to a different type. Unless doing so + // would cause a type conversion of one of our arguments, change this call to + // be a direct call with arguments casted to the appropriate types. + // + const FunctionType *FT = Callee->getFunctionType(); + const Type *OldRetTy = Caller->getType(); + + // Check to see if we are changing the return type... + if (OldRetTy != FT->getReturnType()) { + if (Callee->isExternal() && + !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) && + !Caller->use_empty()) + return false; // Cannot transform this return value... + + // If the callsite is an invoke instruction, and the return value is used by + // a PHI node in a successor, we cannot change the return type of the call + // because there is no place to put the cast instruction (without breaking + // the critical edge). Bail out in this case. + if (!Caller->use_empty()) + if (InvokeInst *II = dyn_cast(Caller)) + for (Value::use_iterator UI = II->use_begin(), E = II->use_end(); + UI != E; ++UI) + if (PHINode *PN = dyn_cast(*UI)) + if (PN->getParent() == II->getNormalDest() || + PN->getParent() == II->getUnwindDest()) + return false; + } + + unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin()); + unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs); + + CallSite::arg_iterator AI = CS.arg_begin(); + for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) { + const Type *ParamTy = FT->getParamType(i); + bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy); + if (Callee->isExternal() && !isConvertible) return false; + } + + if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() && + Callee->isExternal()) + return false; // Do not delete arguments unless we have a function body... + + // Okay, we decided that this is a safe thing to do: go ahead and start + // inserting cast instructions as necessary... + std::vector Args; + Args.reserve(NumActualArgs); + + AI = CS.arg_begin(); + for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) { + const Type *ParamTy = FT->getParamType(i); + if ((*AI)->getType() == ParamTy) { + Args.push_back(*AI); + } else { + Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"), + *Caller)); + } + } + + // If the function takes more arguments than the call was taking, add them + // now... + for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) + Args.push_back(Constant::getNullValue(FT->getParamType(i))); + + // If we are removing arguments to the function, emit an obnoxious warning... + if (FT->getNumParams() < NumActualArgs) + if (!FT->isVarArg()) { + std::cerr << "WARNING: While resolving call to function '" + << Callee->getName() << "' arguments were dropped!\n"; + } else { + // Add all of the arguments in their promoted form to the arg list... + for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) { + const Type *PTy = getPromotedType((*AI)->getType()); + if (PTy != (*AI)->getType()) { + // Must promote to pass through va_arg area! + Instruction *Cast = new CastInst(*AI, PTy, "tmp"); + InsertNewInstBefore(Cast, *Caller); + Args.push_back(Cast); + } else { + Args.push_back(*AI); + } + } + } + + if (FT->getReturnType() == Type::VoidTy) + Caller->setName(""); // Void type should not have a name... + + Instruction *NC; + if (InvokeInst *II = dyn_cast(Caller)) { + NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(), + Args, Caller->getName(), Caller); + } else { + NC = new CallInst(Callee, Args, Caller->getName(), Caller); + } + + // Insert a cast of the return type as necessary... + Value *NV = NC; + if (Caller->getType() != NV->getType() && !Caller->use_empty()) { + if (NV->getType() != Type::VoidTy) { + NV = NC = new CastInst(NC, Caller->getType(), "tmp"); + + // If this is an invoke instruction, we should insert it after the first + // non-phi, instruction in the normal successor block. + if (InvokeInst *II = dyn_cast(Caller)) { + BasicBlock::iterator I = II->getNormalDest()->begin(); + while (isa(I)) ++I; + InsertNewInstBefore(NC, *I); + } else { + // Otherwise, it's a call, just insert cast right after the call instr + InsertNewInstBefore(NC, *Caller); + } + AddUsersToWorkList(*Caller); + } else { + NV = Constant::getNullValue(Caller->getType()); + } + } + + if (Caller->getType() != Type::VoidTy && !Caller->use_empty()) + Caller->replaceAllUsesWith(NV); + Caller->getParent()->getInstList().erase(Caller); + removeFromWorkList(Caller); + return true; + } + + + + // PHINode simplification + // + Instruction *InstCombiner::visitPHINode(PHINode &PN) { + if (Value *V = hasConstantValue(&PN)) + return ReplaceInstUsesWith(PN, V); + + // If the only user of this instruction is a cast instruction, and all of the + // incoming values are constants, change this PHI to merge together the casted + // constants. + if (PN.hasOneUse()) + if (CastInst *CI = dyn_cast(PN.use_back())) + if (CI->getType() != PN.getType()) { // noop casts will be folded + bool AllConstant = true; + for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) + if (!isa(PN.getIncomingValue(i))) { + AllConstant = false; + break; + } + if (AllConstant) { + // Make a new PHI with all casted values. + PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN); + for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { + Constant *OldArg = cast(PN.getIncomingValue(i)); + New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()), + PN.getIncomingBlock(i)); + } + + // Update the cast instruction. + CI->setOperand(0, New); + WorkList.push_back(CI); // revisit the cast instruction to fold. + WorkList.push_back(New); // Make sure to revisit the new Phi + return &PN; // PN is now dead! + } + } + return 0; + } + + static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy, + Instruction *InsertPoint, + InstCombiner *IC) { + unsigned PS = IC->getTargetData().getPointerSize(); + const Type *VTy = V->getType(); + Instruction *Cast; + if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS) + // We must insert a cast to ensure we sign-extend. + V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(), + V->getName()), *InsertPoint); + return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()), + *InsertPoint); + } + + + Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) { + Value *PtrOp = GEP.getOperand(0); + // Is it 'getelementptr %P, long 0' or 'getelementptr %P' + // If so, eliminate the noop. + if (GEP.getNumOperands() == 1) + return ReplaceInstUsesWith(GEP, PtrOp); + + bool HasZeroPointerIndex = false; + if (Constant *C = dyn_cast(GEP.getOperand(1))) + HasZeroPointerIndex = C->isNullValue(); + + if (GEP.getNumOperands() == 2 && HasZeroPointerIndex) + return ReplaceInstUsesWith(GEP, PtrOp); + + // Eliminate unneeded casts for indices. + bool MadeChange = false; + gep_type_iterator GTI = gep_type_begin(GEP); + for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) + if (isa(*GTI)) { + if (CastInst *CI = dyn_cast(GEP.getOperand(i))) { + Value *Src = CI->getOperand(0); + const Type *SrcTy = Src->getType(); + const Type *DestTy = CI->getType(); + if (Src->getType()->isInteger()) { + if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) { + // We can always eliminate a cast from ulong or long to the other. + // We can always eliminate a cast from uint to int or the other on + // 32-bit pointer platforms. + if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) { + MadeChange = true; + GEP.setOperand(i, Src); + } + } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() && + SrcTy->getPrimitiveSize() == 4) { + // We can always eliminate a cast from int to [u]long. We can + // eliminate a cast from uint to [u]long iff the target is a 32-bit + // pointer target. + if (SrcTy->isSigned() || + SrcTy->getPrimitiveSize() >= TD->getPointerSize()) { + MadeChange = true; + GEP.setOperand(i, Src); + } + } + } + } + // If we are using a wider index than needed for this platform, shrink it + // to what we need. If the incoming value needs a cast instruction, + // insert it. This explicit cast can make subsequent optimizations more + // obvious. + Value *Op = GEP.getOperand(i); + if (Op->getType()->getPrimitiveSize() > TD->getPointerSize()) + if (Constant *C = dyn_cast(Op)) { + GEP.setOperand(i, ConstantExpr::getCast(C, + TD->getIntPtrType()->getSignedVersion())); + MadeChange = true; + } else { + Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(), + Op->getName()), GEP); + GEP.setOperand(i, Op); + MadeChange = true; + } + + // If this is a constant idx, make sure to canonicalize it to be a signed + // operand, otherwise CSE and other optimizations are pessimized. + if (ConstantUInt *CUI = dyn_cast(Op)) { + GEP.setOperand(i, ConstantExpr::getCast(CUI, + CUI->getType()->getSignedVersion())); + MadeChange = true; + } + } + if (MadeChange) return &GEP; + + // Combine Indices - If the source pointer to this getelementptr instruction + // is a getelementptr instruction, combine the indices of the two + // getelementptr instructions into a single instruction. + // + std::vector SrcGEPOperands; + if (GetElementPtrInst *Src = dyn_cast(PtrOp)) { + SrcGEPOperands.assign(Src->op_begin(), Src->op_end()); + } else if (ConstantExpr *CE = dyn_cast(PtrOp)) { + if (CE->getOpcode() == Instruction::GetElementPtr) + SrcGEPOperands.assign(CE->op_begin(), CE->op_end()); + } + + if (!SrcGEPOperands.empty()) { + // Note that if our source is a gep chain itself that we wait for that + // chain to be resolved before we perform this transformation. This + // avoids us creating a TON of code in some cases. + // + if (isa(SrcGEPOperands[0]) && + cast(SrcGEPOperands[0])->getNumOperands() == 2) + return 0; // Wait until our source is folded to completion. + + std::vector Indices; + + // Find out whether the last index in the source GEP is a sequential idx. + bool EndsWithSequential = false; + for (gep_type_iterator I = gep_type_begin(*cast(PtrOp)), + E = gep_type_end(*cast(PtrOp)); I != E; ++I) + EndsWithSequential = !isa(*I); + + // Can we combine the two pointer arithmetics offsets? + if (EndsWithSequential) { + // Replace: gep (gep %P, long B), long A, ... + // With: T = long A+B; gep %P, T, ... + // + Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1); + if (SO1 == Constant::getNullValue(SO1->getType())) { + Sum = GO1; + } else if (GO1 == Constant::getNullValue(GO1->getType())) { + Sum = SO1; + } else { + // If they aren't the same type, convert both to an integer of the + // target's pointer size. + if (SO1->getType() != GO1->getType()) { + if (Constant *SO1C = dyn_cast(SO1)) { + SO1 = ConstantExpr::getCast(SO1C, GO1->getType()); + } else if (Constant *GO1C = dyn_cast(GO1)) { + GO1 = ConstantExpr::getCast(GO1C, SO1->getType()); + } else { + unsigned PS = TD->getPointerSize(); + Instruction *Cast; + if (SO1->getType()->getPrimitiveSize() == PS) { + // Convert GO1 to SO1's type. + GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this); + + } else if (GO1->getType()->getPrimitiveSize() == PS) { + // Convert SO1 to GO1's type. + SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this); + } else { + const Type *PT = TD->getIntPtrType(); + SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this); + GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this); + } + } + } + if (isa(SO1) && isa(GO1)) + Sum = ConstantExpr::getAdd(cast(SO1), cast(GO1)); + else { + Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum"); + InsertNewInstBefore(cast(Sum), GEP); + } + } + + // Recycle the GEP we already have if possible. + if (SrcGEPOperands.size() == 2) { + GEP.setOperand(0, SrcGEPOperands[0]); + GEP.setOperand(1, Sum); + return &GEP; + } else { + Indices.insert(Indices.end(), SrcGEPOperands.begin()+1, + SrcGEPOperands.end()-1); + Indices.push_back(Sum); + Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end()); + } + } else if (isa(*GEP.idx_begin()) && + cast(*GEP.idx_begin())->isNullValue() && + SrcGEPOperands.size() != 1) { + // Otherwise we can do the fold if the first index of the GEP is a zero + Indices.insert(Indices.end(), SrcGEPOperands.begin()+1, + SrcGEPOperands.end()); + Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end()); + } + + if (!Indices.empty()) + return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName()); + + } else if (GlobalValue *GV = dyn_cast(PtrOp)) { + // GEP of global variable. If all of the indices for this GEP are + // constants, we can promote this to a constexpr instead of an instruction. + + // Scan for nonconstants... + std::vector Indices; + User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); + for (; I != E && isa(*I); ++I) + Indices.push_back(cast(*I)); + + if (I == E) { // If they are all constants... + Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices); + + // Replace all uses of the GEP with the new constexpr... + return ReplaceInstUsesWith(GEP, CE); + } + } else if (ConstantExpr *CE = dyn_cast(PtrOp)) { + if (CE->getOpcode() == Instruction::Cast) { + if (HasZeroPointerIndex) { + // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ... + // into : GEP [10 x ubyte]* X, long 0, ... + // + // This occurs when the program declares an array extern like "int X[];" + // + Constant *X = CE->getOperand(0); + const PointerType *CPTy = cast(CE->getType()); + if (const PointerType *XTy = dyn_cast(X->getType())) + if (const ArrayType *XATy = + dyn_cast(XTy->getElementType())) + if (const ArrayType *CATy = + dyn_cast(CPTy->getElementType())) + if (CATy->getElementType() == XATy->getElementType()) { + // At this point, we know that the cast source type is a pointer + // to an array of the same type as the destination pointer + // array. Because the array type is never stepped over (there + // is a leading zero) we can fold the cast into this GEP. + GEP.setOperand(0, X); + return &GEP; + } + } + } + } + + return 0; + } + + Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) { + // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1 + if (AI.isArrayAllocation()) // Check C != 1 + if (const ConstantUInt *C = dyn_cast(AI.getArraySize())) { + const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue()); + AllocationInst *New = 0; + + // Create and insert the replacement instruction... + if (isa(AI)) + New = new MallocInst(NewTy, 0, AI.getName()); + else { + assert(isa(AI) && "Unknown type of allocation inst!"); + New = new AllocaInst(NewTy, 0, AI.getName()); + } + + InsertNewInstBefore(New, AI); + + // Scan to the end of the allocation instructions, to skip over a block of + // allocas if possible... + // + BasicBlock::iterator It = New; + while (isa(*It)) ++It; + + // Now that I is pointing to the first non-allocation-inst in the block, + // insert our getelementptr instruction... + // + std::vector Idx(2, Constant::getNullValue(Type::IntTy)); + Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It); + + // Now make everything use the getelementptr instead of the original + // allocation. + return ReplaceInstUsesWith(AI, V); + } + + // If alloca'ing a zero byte object, replace the alloca with a null pointer. + // Note that we only do this for alloca's, because malloc should allocate and + // return a unique pointer, even for a zero byte allocation. + if (isa(AI) && AI.getAllocatedType()->isSized() && + TD->getTypeSize(AI.getAllocatedType()) == 0) + return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType())); + + return 0; + } + + Instruction *InstCombiner::visitFreeInst(FreeInst &FI) { + Value *Op = FI.getOperand(0); + + // Change free * (cast * X to *) into free * X + if (CastInst *CI = dyn_cast(Op)) + if (isa(CI->getOperand(0)->getType())) { + FI.setOperand(0, CI->getOperand(0)); + return &FI; + } + + // If we have 'free null' delete the instruction. This can happen in stl code + // when lots of inlining happens. + if (isa(Op)) + return EraseInstFromFunction(FI); + + return 0; + } + + + /// GetGEPGlobalInitializer - Given a constant, and a getelementptr + /// constantexpr, return the constant value being addressed by the constant + /// expression, or null if something is funny. + /// + static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) { + if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType())) + return 0; // Do not allow stepping over the value! + + // Loop over all of the operands, tracking down which value we are + // addressing... + gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE); + for (++I; I != E; ++I) + if (const StructType *STy = dyn_cast(*I)) { + ConstantUInt *CU = cast(I.getOperand()); + assert(CU->getValue() < STy->getNumElements() && + "Struct index out of range!"); + if (ConstantStruct *CS = dyn_cast(C)) { + C = CS->getOperand(CU->getValue()); + } else if (isa(C)) { + C = Constant::getNullValue(STy->getElementType(CU->getValue())); + } else { + return 0; + } + } else if (ConstantInt *CI = dyn_cast(I.getOperand())) { + const ArrayType *ATy = cast(*I); + if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0; + if (ConstantArray *CA = dyn_cast(C)) + C = CA->getOperand(CI->getRawValue()); + else if (isa(C)) + C = Constant::getNullValue(ATy->getElementType()); + else + return 0; + } else { + return 0; + } + return C; + } + + static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) { + User *CI = cast(LI.getOperand(0)); + + const Type *DestPTy = cast(CI->getType())->getElementType(); + if (const PointerType *SrcTy = + dyn_cast(CI->getOperand(0)->getType())) { + const Type *SrcPTy = SrcTy->getElementType(); + if (SrcPTy->isSized() && DestPTy->isSized() && + IC.getTargetData().getTypeSize(SrcPTy) == + IC.getTargetData().getTypeSize(DestPTy) && + (SrcPTy->isInteger() || isa(SrcPTy)) && + (DestPTy->isInteger() || isa(DestPTy))) { + // Okay, we are casting from one integer or pointer type to another of + // the same size. Instead of casting the pointer before the load, cast + // the result of the loaded value. + Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0), + CI->getName(), + LI.isVolatile()),LI); + // Now cast the result of the load. + return new CastInst(NewLoad, LI.getType()); + } + } + return 0; + } + + /// isSafeToLoadUnconditionally - Return true if we know that executing a load + /// from this value cannot trap. If it is not obviously safe to load from the + /// specified pointer, we do a quick local scan of the basic block containing + /// ScanFrom, to determine if the address is already accessed. + static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) { + // If it is an alloca or global variable, it is always safe to load from. + if (isa(V) || isa(V)) return true; + + // Otherwise, be a little bit agressive by scanning the local block where we + // want to check to see if the pointer is already being loaded or stored + // from/to. If so, the previous load or store would have already trapped, + // so there is no harm doing an extra load (also, CSE will later eliminate + // the load entirely). + BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin(); + + while (BBI != E) { + --BBI; + + if (LoadInst *LI = dyn_cast(BBI)) { + if (LI->getOperand(0) == V) return true; + } else if (StoreInst *SI = dyn_cast(BBI)) + if (SI->getOperand(1) == V) return true; + + } + return false; + } + + Instruction *InstCombiner::visitLoadInst(LoadInst &LI) { + Value *Op = LI.getOperand(0); + + if (Constant *C = dyn_cast(Op)) + if (C->isNullValue() && !LI.isVolatile()) // load null -> 0 + return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType())); + + // Instcombine load (constant global) into the value loaded... + if (GlobalVariable *GV = dyn_cast(Op)) + if (GV->isConstant() && !GV->isExternal()) + return ReplaceInstUsesWith(LI, GV->getInitializer()); + + // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded... + if (ConstantExpr *CE = dyn_cast(Op)) + if (CE->getOpcode() == Instruction::GetElementPtr) { + if (GlobalVariable *GV = dyn_cast(CE->getOperand(0))) + if (GV->isConstant() && !GV->isExternal()) + if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE)) + return ReplaceInstUsesWith(LI, V); + } else if (CE->getOpcode() == Instruction::Cast) { + if (Instruction *Res = InstCombineLoadCast(*this, LI)) + return Res; + } + + // load (cast X) --> cast (load X) iff safe + if (CastInst *CI = dyn_cast(Op)) + if (Instruction *Res = InstCombineLoadCast(*this, LI)) + return Res; + + if (!LI.isVolatile() && Op->hasOneUse()) { + // Change select and PHI nodes to select values instead of addresses: this + // helps alias analysis out a lot, allows many others simplifications, and + // exposes redundancy in the code. + // + // Note that we cannot do the transformation unless we know that the + // introduced loads cannot trap! Something like this is valid as long as + // the condition is always false: load (select bool %C, int* null, int* %G), + // but it would not be valid if we transformed it to load from null + // unconditionally. + // + if (SelectInst *SI = dyn_cast(Op)) { + // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2). + if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) && + isSafeToLoadUnconditionally(SI->getOperand(2), SI)) { + Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1), + SI->getOperand(1)->getName()+".val"), LI); + Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2), + SI->getOperand(2)->getName()+".val"), LI); + return new SelectInst(SI->getCondition(), V1, V2); + } + + // load (select (cond, null, P)) -> load P + if (Constant *C = dyn_cast(SI->getOperand(1))) + if (C->isNullValue()) { + LI.setOperand(0, SI->getOperand(2)); + return &LI; + } + + // load (select (cond, P, null)) -> load P + if (Constant *C = dyn_cast(SI->getOperand(2))) + if (C->isNullValue()) { + LI.setOperand(0, SI->getOperand(1)); + return &LI; + } + + } else if (PHINode *PN = dyn_cast(Op)) { + // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3) + bool Safe = PN->getParent() == LI.getParent(); + + // Scan all of the instructions between the PHI and the load to make + // sure there are no instructions that might possibly alter the value + // loaded from the PHI. + if (Safe) { + BasicBlock::iterator I = &LI; + for (--I; !isa(I); --I) + if (isa(I) || isa(I)) { + Safe = false; + break; + } + } + + for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i) + if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i), + PN->getIncomingBlock(i)->getTerminator())) + Safe = false; + + if (Safe) { + // Create the PHI. + PHINode *NewPN = new PHINode(LI.getType(), PN->getName()); + InsertNewInstBefore(NewPN, *PN); + std::map LoadMap; // Don't insert duplicate loads + + for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { + BasicBlock *BB = PN->getIncomingBlock(i); + Value *&TheLoad = LoadMap[BB]; + if (TheLoad == 0) { + Value *InVal = PN->getIncomingValue(i); + TheLoad = InsertNewInstBefore(new LoadInst(InVal, + InVal->getName()+".val"), + *BB->getTerminator()); + } + NewPN->addIncoming(TheLoad, BB); + } + return ReplaceInstUsesWith(LI, NewPN); + } + } + } + return 0; + } + + + Instruction *InstCombiner::visitBranchInst(BranchInst &BI) { + // Change br (not X), label True, label False to: br X, label False, True + Value *X; + BasicBlock *TrueDest; + BasicBlock *FalseDest; + if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) && + !isa(X)) { + // Swap Destinations and condition... + BI.setCondition(X); + BI.setSuccessor(0, FalseDest); + BI.setSuccessor(1, TrueDest); + return &BI; + } + + // Cannonicalize setne -> seteq + Instruction::BinaryOps Op; Value *Y; + if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)), + TrueDest, FalseDest))) + if ((Op == Instruction::SetNE || Op == Instruction::SetLE || + Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) { + SetCondInst *I = cast(BI.getCondition()); + std::string Name = I->getName(); I->setName(""); + Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op); + Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I); + // Swap Destinations and condition... + BI.setCondition(NewSCC); + BI.setSuccessor(0, FalseDest); + BI.setSuccessor(1, TrueDest); + removeFromWorkList(I); + I->getParent()->getInstList().erase(I); + WorkList.push_back(cast(NewSCC)); + return &BI; + } + + return 0; + } + + Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) { + Value *Cond = SI.getCondition(); + if (Instruction *I = dyn_cast(Cond)) { + if (I->getOpcode() == Instruction::Add) + if (ConstantInt *AddRHS = dyn_cast(I->getOperand(1))) { + // change 'switch (X+4) case 1:' into 'switch (X) case -3' + for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) + SI.setOperand(i, ConstantExpr::getSub(cast(SI.getOperand(i)), + AddRHS)); + SI.setOperand(0, I->getOperand(0)); + WorkList.push_back(I); + return &SI; + } + } + return 0; + } + + + void InstCombiner::removeFromWorkList(Instruction *I) { + WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I), + WorkList.end()); + } + + bool InstCombiner::runOnFunction(Function &F) { + bool Changed = false; + TD = &getAnalysis(); + + for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) + WorkList.push_back(&*i); + + + while (!WorkList.empty()) { + Instruction *I = WorkList.back(); // Get an instruction from the worklist + WorkList.pop_back(); + + // Check to see if we can DCE or ConstantPropagate the instruction... + // Check to see if we can DIE the instruction... + if (isInstructionTriviallyDead(I)) { + // Add operands to the worklist... + if (I->getNumOperands() < 4) + AddUsesToWorkList(*I); + ++NumDeadInst; + + I->getParent()->getInstList().erase(I); + removeFromWorkList(I); + continue; + } + + // Instruction isn't dead, see if we can constant propagate it... + if (Constant *C = ConstantFoldInstruction(I)) { + // Add operands to the worklist... + AddUsesToWorkList(*I); + ReplaceInstUsesWith(*I, C); + + ++NumConstProp; + I->getParent()->getInstList().erase(I); + removeFromWorkList(I); + continue; + } + + // Now that we have an instruction, try combining it to simplify it... + if (Instruction *Result = visit(*I)) { + ++NumCombined; + // Should we replace the old instruction with a new one? + if (Result != I) { + DEBUG(std::cerr << "IC: Old = " << *I + << " New = " << *Result); + + // Everything uses the new instruction now. + I->replaceAllUsesWith(Result); + + // Push the new instruction and any users onto the worklist. + WorkList.push_back(Result); + AddUsersToWorkList(*Result); + + // Move the name to the new instruction first... + std::string OldName = I->getName(); I->setName(""); + Result->setName(OldName); + + // Insert the new instruction into the basic block... + BasicBlock *InstParent = I->getParent(); + InstParent->getInstList().insert(I, Result); + + // Make sure that we reprocess all operands now that we reduced their + // use counts. + for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) + if (Instruction *OpI = dyn_cast(I->getOperand(i))) + WorkList.push_back(OpI); + + // Instructions can end up on the worklist more than once. Make sure + // we do not process an instruction that has been deleted. + removeFromWorkList(I); + + // Erase the old instruction. + InstParent->getInstList().erase(I); + } else { + DEBUG(std::cerr << "IC: MOD = " << *I); + + // If the instruction was modified, it's possible that it is now dead. + // if so, remove it. + if (isInstructionTriviallyDead(I)) { + // Make sure we process all operands now that we are reducing their + // use counts. + for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) + if (Instruction *OpI = dyn_cast(I->getOperand(i))) + WorkList.push_back(OpI); + + // Instructions may end up in the worklist more than once. Erase all + // occurrances of this instruction. + removeFromWorkList(I); + I->getParent()->getInstList().erase(I); + } else { + WorkList.push_back(Result); + AddUsersToWorkList(*Result); + } + } + Changed = true; + } + } + + return Changed; + } + + FunctionPass *llvm::createInstructionCombiningPass() { + return new InstCombiner(); + } + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/Makefile:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/Makefile Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = agrep + RUN_OPTIONS = -2 int $(BUILD_SRC_DIR)/InstructionCombining.cpp.txt + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/README diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/README:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/README Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,88 ---- + This is version 2.04 of agrep - a new tool for fast + text searching allowing errors. + agrep is similar to egrep (or grep or fgrep), but it is much more general + (and usually faster). + The main changes from version 1.1 are 1) incorporating Boyer-Moore + type filtering to speed up search considerably, 2) allowing multi patterns + via the -f option; this is similar to fgrep, but from our experience + agrep is much faster, 3) searching for "best match" without having to + specify the number of errors allowed, and 4) ascii is no longer required. + Several more options were added. + + To compile, simply run make in the agrep directory after untar'ing + the tar file (tar -xf agrep-2.04.tar will do it). + + The three most significant features of agrep that are not supported by + the grep family are + 1) the ability to search for approximate patterns; + for example, "agrep -2 homogenos foo" will find homogeneous as well + as any other word that can be obtained from homogenos with at most + 2 substitutions, insertions, or deletions. + "agrep -B homogenos foo" will generate a message of the form + best match has 2 errors, there are 5 matches, output them? (y/n) + 2) agrep is record oriented rather than just line oriented; a record + is by default a line, but it can be user defined; + for example, "agrep -d '^From ' 'pizza' mbox" + outputs all mail messages that contain the keyword "pizza". + Another example: "agrep -d '$$' pattern foo" will output all + paragraphs (separated by an empty line) that contain pattern. + 3) multiple patterns with AND (or OR) logic queries. + For example, "agrep -d '^From ' 'burger,pizza' mbox" + outputs all mail messages containing at least one of the + two keywords (, stands for OR). + "agrep -d '^From ' 'good;pizza' mbox" outputs all mail messages + containing both keywords. + + Putting these options together one can ask queries like + + agrep -d '$$' -2 ';TheAuthor;Curriculum;<198[5-9]>' bib + + which outputs all paragraphs referencing articles in CACM between + 1985 and 1989 by TheAuthor dealing with curriculum. + Two errors are allowed, but they cannot be in either CACM or the year + (the <> brackets forbid errors in the pattern between them). + + Other features include searching for regular expressions (with or + without errors), unlimited wild cards, limiting the errors to only + insertions or only substitutions or any combination, + allowing each deletion, for example, to be counted as, say, + 2 substitutions or 3 insertions, restricting parts of the query + to be exact and parts to be approximate, and many more. + + agrep is available by anonymous ftp from cs.arizona.edu (IP 192.12.69.5) + as agrep/agrep-2.04.tar.Z (or in uncompressed form as agrep/agrep-2.04.tar). + The tar file contains the source code (in C), man pages (agrep.1), + and two additional files, agrep.algorithms and agrep.chronicle, + giving more information. + The agrep directory also includes two postscript files: + agrep.ps.1 is a technical report from June 1991 + describing the design and implementation of agrep; + agrep.ps.2 is a copy of the paper as appeared in the 1992 + Winter USENIX conference. + + Please mail bug reports (or any other comments) + to sw at cs.arizona.edu or to udi at cs.arizona.edu. + + We would appreciate if users notify us (at the address above) + of any extensions, improvements, or interesting uses of this software. + + January 17, 1992 + + + BUGS_fixed/option_update + + 1. remove multiple definitions of some global variables. + 2. fix a bug in -G option. + 3. fix a bug in -w option. + January 23, 1992 + + 4. fix a bug in pipeline input. + 5. make the definition of word-delimiter consistant. + March 16, 1992 + + 6. add option '-y' which, if specified with -B option, will always + output the best-matches without a prompt. + April 10, 1992 + + 7. fix a bug regarding exit status. + April 15, 1992 Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/agrep Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/agrep.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/agrep.h:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/agrep.h Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,56 ---- + #include + #include + #include + #include "re.h" + /* + extern unsigned char *strcpy(), *strncpy(), *strcat(); + extern int strlen(); + */ + #include + #define CHAR unsigned char + #define MAXPAT 128 + #define MAXPATT 256 + #define MAXDELIM 8 /* Max size of a delimiter pattern */ + #define SHORTREG 15 + #define MAXREG 30 + #define MAXNAME 256 + #define Max_Pats 12 /* max num of patterns */ + #define Max_Keys 12 /* max num of keywords */ + #define Max_Psize 128 /* max size of a pattern counting all the characters */ + #define Max_Keyword 31 /* the max size of a keyword */ + #define WORD 32 /* the size of a word */ + #define MaxError 8 /* the max number of errors allowed */ + #define MaxRerror 4 /* the max number of erros for regular expression */ + #define MaxDelimit 16 /* the max raw length of a user defined delimiter */ + #define BlockSize 49152 + #define Max_record 49152 + #define SIZE 16384 /* BlockSIze in sgrep */ + #define MAXLINE 1024 /* maxline in sgrep */ + #define Maxline 1024 + #define RBLOCK 8192 + #define RMAXLINE 1024 + #define MaxNext 66000 + #define ON 1 + #define OFF 0 + #define Compl 1 + #define Maxresult 10000 + #define MaxCan 2500 + #define MAXSYM 256 /* ASCII */ + #define WORDB 241 /* -w option */ + #define LPARENT 242 /* ( */ + #define RPARENT 243 /* ) */ + #define LRANGE 244 /* [ */ + #define RRANGE 245 /* ] */ + #define LANGLE 246 /* < */ + #define RANGLE 247 /* > */ + #define NOTSYM 248 /* ^ */ + #define WILDCD 249 /* wildcard */ + #define ORSYM 250 /* | */ + #define ORPAT 251 /* , */ + #define ANDPAT 252 /* ; */ + #define STAR 253 /* closure */ + #define HYPHEN 237 /* - */ + #define NOCARE 238 /* . */ + #define NNLINE 239 /* special symbol for newline in begin of pattern*/ + /* matches '\n' and NNLINE */ + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/asearch.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/asearch.c:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/asearch.c Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,315 ---- + /* Copyright (c) 1991 Sun Wu and Udi Manber. All Rights Reserved. */ + #include "agrep.h" + + extern unsigned Init1, Init[], Mask[], endposition, D_endpos, AND, NO_ERR_MASK; + extern int DELIMITER, FILENAMEONLY, INVERSE; + extern CHAR CurrentFileName[]; + extern int I, num_of_matched, TRUNCATE; + + extern int fill_buf(int fd, unsigned char *buf, int record_size); + extern void output(register CHAR *buffer, int i1, int i2, int j); + + void asearch0(CHAR old_D_pat[], int text, register unsigned D) + { + register unsigned i, c, r1, r2, CMask, r_NO_ERR, r_Init1, end, endpos; + unsigned A[MaxError+2], B[MaxError+2]; + unsigned D_Mask; + int D_length, FIRSTROUND, ResidueSize, lasti, l, k, j=0; + int printout_end; + CHAR buffer[BlockSize+Max_record+1]; + + D_length = strlen(old_D_pat); + buffer[Max_record-1] = '\n'; + D_Mask = D_endpos; + for ( i=1; i 0) + { i = Max_record; end = Max_record + l ; + if (FIRSTROUND) { + i = Max_record - 1; + FIRSTROUND = OFF; } + if (l < BlockSize) { + strncpy(buffer+end, old_D_pat, D_length); + buffer[end+D_length] = '\0'; + end = end + D_length; } + while (i < end ) + { + c = buffer[i++]; + CMask = Mask[c]; + r1 = B[0] & r_Init1; + A[0] = (((B[0] >> 1)) & CMask | r1 ) ; + for(k=1; k<=D; k++) { + r1 = r_Init1 & B[k]; + r2 = B[k-1] | (((A[k-1]|B[k-1])>>1) & r_NO_ERR); + A[k] = ((B[k] >> 1) & CMask) | r2 | r1; + } + if(A[0] & endpos) { + j++; + r1 = A[D]; + if(((AND == 1) && ((r1 & endposition) == endposition)) || ((AND == 0) && (r1 & endposition)) ^ INVERSE ) + { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; } + printout_end = i - D_length - 1; + if(!(lasti >= Max_record + l - 1)) + output(buffer, lasti, printout_end, j); + } + lasti = i - D_length; /* point to starting position of D_pat */ + for(k=0; k<= D; k++) { + B[k] = Init[0]; + } + r1 = B[0] & r_Init1; + A[0] = (((B[0]>>1) & CMask) | r1) & D_Mask; + for(k=1; k<= D; k++) { + r1 = Init1 & B[k]; + r2 = B[k-1] | (((A[k-1] | B[k-1])>>1)&r_NO_ERR); + A[k] = (((B[k]>>1)&CMask) | r1 | r2) ; + } + } + c = buffer[i++]; + CMask = Mask[c]; + r1 = r_Init1 & A[0]; + B[0] = ((A[0] >> 1 ) & CMask) | r1; + for(k=1; k<=D; k++) { + r1 = r_Init1 & A[k]; + r2 = A[k-1] | (((A[k-1]|B[k-1])>>1) & r_NO_ERR); + B[k] = ((A[k] >> 1) & CMask) | r2 | r1; + } + if(B[0] & endpos) { + j++; + r1 = B[D]; + if(((AND == 1) && ((r1 & endposition) == endposition)) || ((AND == 0) && (r1 & endposition)) ^ INVERSE ) + { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; } + printout_end = i - D_length -1 ; + if(!(lasti >= Max_record + l - 1)) + output(buffer, lasti, printout_end, j); + } + lasti = i - D_length ; + for(k=0; k<= D; k++) { + A[k] = Init[0]; + } + r1 = A[0] & r_Init1; + B[0] = (((A[0]>>1)&CMask) | r1) & D_Mask; + for(k=1; k<= D; k++) { + r1 = r_Init1 & A[k]; + r2 = A[k-1] | (((A[k-1] | B[k-1])>>1)&r_NO_ERR); + B[k] = (((A[k]>>1)&CMask) | r1 | r2) ; + } + } + } + if(l < BlockSize) { + lasti = Max_record; + } + else { + ResidueSize = Max_record + l - lasti; + if(ResidueSize > Max_record) { + ResidueSize = Max_record; + TRUNCATE = ON; } + strncpy(buffer+Max_record-ResidueSize, buffer+lasti, ResidueSize); + lasti = Max_record - ResidueSize; + if(lasti == 0) lasti = 1; + } + } + return; + } + + void asearch(CHAR old_D_pat[], int text, register unsigned D) + { + register unsigned i, c, r1, r2, CMask, r_NO_ERR, r_Init1; + register unsigned A0, B0, A1, B1, endpos; + unsigned A2, B2, A3, B3, A4, B4; + unsigned A[MaxError+1], B[MaxError+1]; + unsigned D_Mask; + unsigned end; + int D_length, FIRSTROUND, ResidueSize, lasti, l, k, j=0; + int printout_end; + CHAR buffer[2*Max_record+1]; + + if (I == 0) Init1 = 037777777777; + if(D > 4) { + asearch0(old_D_pat, text, D); + return; } + D_length = strlen(old_D_pat); + buffer[Max_record-1] = '\n'; + D_Mask = D_endpos; + for ( i=1; i 0) + { i = Max_record; end = Max_record + l ; + if (FIRSTROUND) { + i = Max_record - 1; + if(DELIMITER) { + for(k=0; k=D_length) j--; + } + FIRSTROUND = OFF; } + if (l < BlockSize) { + strncpy(buffer+end, old_D_pat, D_length); + buffer[end+D_length] = '\0'; + end = end + D_length; } + while (i < end ) + { + c = buffer[i]; + CMask = Mask[c]; + r1 = r_Init1 & B0; + A0 = ((B0 >>1 ) & CMask) | r1; + r1 = r_Init1 & B1; + r2 = B0 | (((A0 | B0) >> 1) & r_NO_ERR); + A1 = ((B1 >>1 ) & CMask) | r2 | r1 ; + if(D == 1) goto Nextchar; + r1 = r_Init1 & B2; + r2 = B1 | (((A1 | B1) >> 1) & r_NO_ERR); + A2 = ((B2 >>1 ) & CMask) | r2 | r1 ; + if(D == 2) goto Nextchar; + r1 = r_Init1 & B3; + r2 = B2 | (((A2 | B2) >> 1) & r_NO_ERR); + A3 = ((B3 >>1 ) & CMask) | r2 | r1 ; + if(D == 3) goto Nextchar; + r1 = r_Init1 & B4; + r2 = B3 | (((A3 | B3) >> 1) & r_NO_ERR); + A4 = ((B4 >>1 ) & CMask) | r2 | r1 ; + if(D == 4) goto Nextchar; + Nextchar: i=i+1; + if(A0 & endpos) { + j++; r1 = A0; + if ( D == 1) r1 = A1; + if ( D == 2) r1 = A2; + if ( D == 3) r1 = A3; + if ( D == 4) r1 = A4; + if(((AND == 1) && ((r1 & endposition) == endposition)) || ((AND == 0) && (r1 & endposition)) ^ INVERSE ) + { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; } + printout_end = i - D_length - 1; + if(!(lasti >= Max_record + l - 1)) + output(buffer, lasti, printout_end, j); + } + lasti = i - D_length; /* point to starting position of D_pat */ + TRUNCATE = OFF; + for(k=0; k<= D; k++) { + B[k] = Init[0]; + } + r1 = B[0] & Init1; + A[0] = (((B[0]>>1) & CMask) | r1) & D_Mask; + for(k=1; k<= D; k++) { + r1 = Init1 & B[k]; + r2 = B[k-1] | (((A[k-1] | B[k-1])>>1)&r_NO_ERR); + A[k] = (((B[k]>>1)&CMask) | r1 | r2) ; + } + A0 = A[0]; B0 = B[0]; A1 = A[1]; B1 = B[1]; A2 = A[2]; B2 = B[2]; + A3 = A[3]; B3 = B[3]; A4 = A[4]; B4 = B[4]; + } + c = buffer[i]; + CMask = Mask[c]; + r1 = r_Init1 & A0; + B0 = ((A0 >> 1 ) & CMask) | r1; + #ifdef DEBUG + printf("Mask = %o, B0 = %o\n", CMask, B0); + #endif + r1 = r_Init1 & A1; + r2 = A0 | (((A0 | B0) >> 1) & r_NO_ERR); + B1 = ((A1 >>1 ) & CMask) | r2 | r1 ; + if(D == 1) goto Nextchar1; + r1 = r_Init1 & A2; + r2 = A1 | (((A1 | B1) >> 1) & r_NO_ERR); + B2 = ((A2 >>1 ) & CMask) | r2 | r1 ; + if(D == 2) goto Nextchar1; + r1 = r_Init1 & A3; + r2 = A2 | (((A2 | B2) >> 1) & r_NO_ERR); + B3 = ((A3 >>1 ) & CMask) | r2 | r1 ; + if(D == 3) goto Nextchar1; + r1 = r_Init1 & A4; + r2 = A3 | (((A3 | B3) >> 1) & r_NO_ERR); + B4 = ((A4 >>1 ) & CMask) | r2 | r1 ; + if(D == 4) goto Nextchar1; + Nextchar1: i=i+1; + if(B0 & endpos) { + j++; r1 = B0; + if ( D == 1) r1 = B1; + if ( D == 2) r1 = B2; + if ( D == 3) r1 = B3; + if ( D == 4) r1 = B4; + if(((AND == 1) && ((r1 & endposition) == endposition)) || ((AND == 0) && (r1 & endposition)) ^ INVERSE ) + { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; } + printout_end = i - D_length -1 ; + if(!(lasti >= Max_record + l - 1)) + output(buffer, lasti, printout_end, j); + } + lasti = i - D_length ; + TRUNCATE = OFF; + for(k=0; k<= D; k++) { + A[k] = Init[0]; + } + r1 = A[0] & Init1; + B[0] = (((A[0]>>1)&CMask) | r1) & D_Mask; + for(k=1; k<= D; k++) { + r1 = Init1 & A[k]; + r2 = A[k-1] | (((A[k-1] | B[k-1])>>1)&r_NO_ERR); + B[k] = (((A[k]>>1)&CMask) | r1 | r2) ; + } + A0 = A[0]; B0 = B[0]; A1 = A[1]; B1 = B[1]; A2 = A[2]; B2 = B[2]; + A3 = A[3]; B3 = B[3]; A4 = A[4]; B4 = B[4]; + } + } + if(l < BlockSize) { + lasti = Max_record ; + } + else { + ResidueSize = Max_record + l - lasti; + if(ResidueSize > Max_record) { + ResidueSize = Max_record; + TRUNCATE = ON; } + strncpy(buffer+Max_record-ResidueSize, buffer+lasti, ResidueSize); + lasti = Max_record - ResidueSize; + if(lasti == 0) lasti = 1; + } + } + return; + } + + + + + /* + int fill_buf(int fd, unsigned char *buf, int record_size) + { + int num_read=1; + int total_read=0; + while(total_read < record_size && num_read > 0) { + num_read = read(fd, buf+total_read, 4096); + total_read = total_read + num_read; + } + return(total_read); + } + */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/asearch1.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/asearch1.c:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/asearch1.c Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,132 ---- + /* Copyright (c) 1991 Sun Wu and Udi Manber. All Rights Reserved. */ + #include "agrep.h" + + extern unsigned Init1, Init[], Mask[], endposition, D_endpos; + extern unsigned NO_ERR_MASK; + extern int TRUNCATE, DELIMITER, AND, I, S, DD, INVERSE, FILENAMEONLY ; + extern char CurrentFileName[]; + extern int num_of_matched; + + extern int fill_buf(int fd, unsigned char *buf, int record_size); + extern void output(register CHAR *buffer, int i1, int i2, int j); + + void asearch1(char old_D_pat[], int Text, register unsigned D) + { + register unsigned end, i, r1, r3, r4, r5, CMask, D_Mask, k, endpos; + register unsigned r_NO_ERR; + unsigned A[MaxError*2+1], B[MaxError*2+1]; + int D_length, ResidueSize, lasti, num_read, FIRSTROUND, j=0; + char buffer[BlockSize+Max_record+1]; + + if(I == 0) Init1 = 037777777777; + if(DD > D) DD = D+1; + if(I > D) I = D+1; + if(S > D) S = D+1; + D_length = strlen(old_D_pat); + buffer[Max_record-1] = '\n'; + + lasti = Max_record; + r_NO_ERR = NO_ERR_MASK; + + D_Mask = D_endpos; + for(i=1 ; i 0) + { + i=Max_record; end = Max_record + num_read; + if(FIRSTROUND) { i = Max_record -1 ; + if(DELIMITER) { + for(k=0; k=D_length) j--; + } + FIRSTROUND = 0; } + if(num_read < BlockSize) { + strncpy(buffer+Max_record+num_read, old_D_pat, D_length); + end = end + D_length; + buffer[end] = '\0'; + } + while (i < end) + { + CMask = Mask[buffer[i++]]; + r1 = Init1 & B[D]; + A[D] = ((B[D] >> 1) & CMask ) | r1; + for(k = r3; k <= r4; k++) /* r3 = D+1, r4 = 2*D */ + { + r5 = B[k]; + r1 = Init1 & r5; + A[k] = ((r5 >> 1) & CMask) | B[k-I] | (((A[k-DD] | B[k-S]) >>1) & r_NO_ERR) | r1 ; + } + if(A[D] & endpos) { + j++; + if(((AND == 1) && ((A[D*2] & endposition) == endposition)) || ((AND == 0) && (A[D*2] & endposition)) ^ INVERSE ) + { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; } + if(lasti < Max_record + num_read) + output(buffer, lasti, i-D_length-1, j); + } + lasti = i - D_length; + TRUNCATE = OFF; + for(k = D; k <= r4 ; k++) A[k] = B[k] = Init[0]; + r1 = Init1 & B[D]; + A[D] = (((B[D] >> 1) & CMask ) | r1) & D_Mask; + for(k = r3; k <= r4; k++) /* r3 = D+1, r4 = 2*D */ + { + r5 = B[k]; + r1 = Init1 & r5; + A[k] = ((r5 >> 1) & CMask) | B[k-I] | (((A[k-DD] | B[k-S]) >>1) & r_NO_ERR) | r1 ; + } + } /* end if (A[D]&endpos) */ + CMask = Mask[buffer[i++]]; + r1 = A[D] & Init1; + B[D] = ((A[D] >> 1) & CMask) | r1; + for(k = r3; k <= r4; k++) + { + r1 = A[k] & Init1; + B[k] = ((A[k] >> 1) & CMask) | A[k-I] | (((B[k-DD] | A[k-S]) >>1)&r_NO_ERR) | r1 ; + } + if(B[D] & endpos) { + j++; + if(((AND == 1) && ((B[r4] & endposition) == endposition)) || ((AND == 0) && (B[r4] & endposition)) ^ INVERSE ) + { if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; } + if(lasti < Max_record + num_read) + output(buffer, lasti, i-D_length-1, j); + } + lasti = i-D_length; + TRUNCATE = OFF; + for(k=D; k <= r4; k++) A[k] = B[k] = Init[0]; + r1 = Init1 & A[D]; + B[D] = (((A[D] >> 1) & CMask ) | r1) & D_Mask; + for(k = r3; k <= r4; k++) /* r3 = D+1, r4 = 2*D */ + { + r5 = A[k]; + r1 = Init1 & r5; + B[k] = ((r5 >> 1) & CMask) | A[k-I] | (((B[k-DD] | A[k-S]) >>1) & r_NO_ERR) | r1 ; + } + } /* end if (B[D]&endpos) */ + } + ResidueSize = Max_record + num_read - lasti; + if(ResidueSize > Max_record) { + ResidueSize = Max_record; + TRUNCATE = ON; + } + strncpy(buffer+Max_record-ResidueSize, buffer+lasti, ResidueSize); + lasti = Max_record - ResidueSize; + if(lasti < 0) lasti = 1; + if(num_read < BlockSize) lasti = Max_record; + } + return; + } + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/bitap.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/bitap.c:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/bitap.c Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,162 ---- + /* Copyright (c) 1991 Sun Wu and Udi Manber. All Rights Reserved. */ + /* if the pattern is not simple fixed pattern, then after preprocessing */ + /* and generating the masks, the program goes here. four cases: 1. */ + /* the pattern is simple regular expression and no error, then do the */ + /* matching here. 2. the pattern is simple regular expression and */ + /* unit cost errors are allowed: then go to asearch(). */ + /* 3. the pattern is simple regular expression, and the edit cost is */ + /* not uniform, then go to asearch1(). */ + /* if the pattern is regular expression then go to re() if M < 14, */ + /* else go to re1() */ + /* input parameters: old_D_pat: delimiter pattern. */ + /* fd, input file descriptor, M: size of pattern, D: # of errors. */ + #include + #include "agrep.h" + + extern unsigned Init1, D_endpos, endposition, Init[], Mask[], Bit[]; + extern int DELIMITER, FILENAMEONLY, D_length, I, AND, REGEX, JUMP, INVERSE; + extern char D_pattern[]; + extern int TRUNCATE, DD, S; + extern char Progname[], CurrentFileName[]; + extern int num_of_matched; + + extern void re(int Text, int M, int D); + extern void re1(int Text, int M, int D); + extern void asearch1(char old_D_pat[], int Text, register unsigned D); + extern void asearch(CHAR old_D_pat[], int text, register unsigned D); + extern int fill_buf(int fd, unsigned char *buf, int record_size); + extern void output(register CHAR *buffer, int i1, int i2, int j); + + /* bitap dispatches job */ + + void bitap(char old_D_pat[], char *Pattern, int fd, int M, int D) + { + char c; + register unsigned r1, r2, r3, CMask, i; + register unsigned end, endpos, r_Init1; + register unsigned D_Mask; + int ResidueSize , FIRSTROUND, lasti, print_end, j, num_read; + int k; + char buffer[Max_record+Max_record+BlockSize]; + D_length = strlen(old_D_pat); + for(i=0; i 4) { + fprintf(stderr, "%s: the maximum number of erorrs allowed for full regular expression is 4\n", Progname); + exit(2); + } + if (M <= SHORTREG) { re(fd, M, D); /* SUN: need to find a even point */ + return; } + else { re1(fd, M, D); + return; } + } + if (D > 0 && JUMP == ON) + { asearch1(old_D_pat, fd, D); return; } + if (D > 0) + { asearch(old_D_pat, fd, D); return; } + if(I == 0) Init1 = 037777777777; + + j=0; + lasti = Max_record; + buffer[Max_record-1] = '\n'; + r_Init1 = Init1; + r1 = r2 = r3 = Init[0]; + endpos = D_endpos; + + buffer[Max_record-1] = '\n'; + D_Mask = D_endpos; + for(i=1 ; i 0) + { + i=Max_record; end = Max_record + num_read; + if(FIRSTROUND) { i = Max_record - 1 ; + + if(DELIMITER) { + for(k=0; k=D_length) j--; + } + + FIRSTROUND = OFF; } + if(num_read < BlockSize) { + strncpy(buffer+Max_record+num_read, old_D_pat, D_length); + end = end + D_length; + buffer[end] = '\0'; + } + while (i < end) + { + c = buffer[i++]; + CMask = Mask[c]; + r1 = r_Init1 & r3; + r2 = (( r3 >> 1 ) & CMask) | r1; + if ( r2 & endpos ) { + j++; + if(((AND == 1) && ((r2 & endposition) == endposition)) || ((AND == 0) && (r2 & endposition)) ^ INVERSE ) + { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; } + print_end = i - D_length - 1; + if(!(lasti >= Max_record+num_read - 1)) + output(buffer, lasti, print_end, j); + } + lasti = i - D_length; + TRUNCATE = OFF; + r2 = r3 = r1 = Init[0]; + r1 = r_Init1 & r3; + r2 = ((( r2 >> 1) & CMask) | r1 ) & D_Mask; + } + c = buffer[i++]; + CMask = Mask[c]; + r1 = r_Init1 & r2; + r3 = (( r2 >> 1 ) & CMask) | r1; + if ( r3 & endpos ) { + j++; + if(((AND == 1) && ((r3 & endposition) == endposition)) || ((AND == 0) && (r3 & endposition)) ^ INVERSE ) + { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; } + print_end = i - D_length - 1; + if(!(lasti >= Max_record+num_read - 1)) + output(buffer, lasti, print_end, j); + } + lasti = i - D_length ; + TRUNCATE = OFF; + r2 = r3 = r1 = Init[0]; + r1 = r_Init1 & r2; + r3 = ((( r2 >> 1) & CMask) | r1 ) & D_Mask; + } + } + ResidueSize = num_read + Max_record - lasti; + if(ResidueSize > Max_record) { + ResidueSize = Max_record; + TRUNCATE = ON; + } + strncpy(buffer+Max_record-ResidueSize, buffer+lasti, ResidueSize); + lasti = Max_record - ResidueSize; + if(lasti < 0) { + lasti = 1; + } + } + return; + } + + int fill_buf(int fd, unsigned char *buf, int record_size) + { + int num_read=1; + int total_read=0; + while(total_read < record_size && num_read > 0) { + num_read = read(fd, buf+total_read, 4096); + total_read = total_read + num_read; + } + return(total_read); + } + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/checkfile.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/checkfile.c:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/checkfile.c Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,101 ---- + /* + * checkfile.c + * takes a file descriptor and checks to see if a file is a regular + * ascii file + * + */ + + #include + #include + #include + #include + #include + #include + + #include "checkfile.h" + + #define MAXLINE 512 + + extern char Progname[]; + extern int errno; + + unsigned char ibuf[MAXLINE]; + + /************************************************************************** + * + * check_file + * input: filename or path (null-terminated character string) + * returns: int (0 if file is a regular file, non-0 if not) + * + * uses stat(2) to see if a file is a regular file. + * + ***************************************************************************/ + + int check_file(char *fname) + { + struct stat buf; + + + if (stat(fname, &buf) != 0) { + if (errno == ENOENT) + return NOSUCHFILE; + else + return STATFAILED; + } else { + /* + if (S_ISREG(buf.st_mode)) { + if ((ftype = samplefile(fname)) == ISASCIIFILE) { + return ISASCIIFILE; + } else if (ftype == ISBINARYFILE) { + return ISBINARYFILE; + } else if (ftype == OPENFAILED) { + return OPENFAILED; + } + } + if (S_ISDIR(buf.st_mode)) { + return ISDIRECTORY; + } + if (S_ISBLK(buf.st_mode)) { + return ISBLOCKFILE; + } + if (S_ISSOCK(buf.st_mode)) { + return ISSOCKET; + } + */ + } + return 0; + } + + /*************************************************************************** + * + * samplefile + * reads in the first part of a file, and checks to see that it is + * all ascii. + * + ***************************************************************************/ + /* + int samplefile(char *fname) + { + char *p; + int numread; + int fd; + + if ((fd = open(fname, O_RDONLY)) == -1) { + fprintf(stderr, "open failed on filename %s\n", fname); + return OPENFAILED; + } + if (numread = read(fd, ibuf, MAXLINE)) { + close(fd); + p = ibuf; + while (isascii(*p++) && --numread); + if (!numread) { + return(ISASCIIFILE); + } else { + return(ISBINARYFILE); + } + } else { + close(fd); + return(ISASCIIFILE); + } + } + */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/checkfile.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/checkfile.h:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/checkfile.h Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,8 ---- + #define NOSUCHFILE -3 + #define OPENFAILED -2 + #define STATFAILED -1 + #define ISASCIIFILE 0 + #define ISDIRECTORY 1 + #define ISBLOCKFILE 2 + #define ISSOCKET 3 + #define ISBINARYFILE 4 Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/compat.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/compat.c:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/compat.c Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,58 ---- + /* test the conflicts between options */ + #include + + extern int FILENAMEONLY, APPROX, PAT_FILE, COUNT, INVERSE, BESTMATCH; + extern FILEOUT; + extern REGEX; + extern DELIMITER; + extern WHOLELINE; + extern LINENUM; + extern I, S, DD; + extern JUMP; + extern char Progname[32]; + + void compat(void) + { + if(BESTMATCH) if(COUNT || FILENAMEONLY || APPROX || PAT_FILE) { + BESTMATCH = 0; + fprintf(stderr, "%s: WARNING!!! -B option ignored when -c, -l, -f, or -# is on\n", Progname); + } + if(PAT_FILE) { + if(APPROX) { + fprintf(stderr, "WARNING!!! approximate matching is not supported with -f option\n"); + } + /* + if(INVERSE) { + fprintf(stderr, "%s: -f and -v are not compatible\n", Progname); + exit(2); + } + */ + if(LINENUM) { + fprintf(stderr, "%s: -f and -n are not compatible\n", Progname); + exit(2); + } + if(DELIMITER) { + fprintf(stderr, "%s: -f and -d are not compatible\n", Progname); + exit(2); + } + } + if(JUMP) { + if(REGEX) { + fprintf(stderr, "WARNING!!! -D#, -I#, or -S# option is ignored for regular expression pattern\n"); + JUMP = 0; + } + if(I == 0 || S == 0 || DD == 0) { + fprintf(stderr, "%s: the error cost cannot be 0\n", Progname); + exit(2); + } + } + if(DELIMITER) { + if(WHOLELINE) { + fprintf(stderr, "%s: -d and -x is not compatible\n", Progname); + exit(2); + } + } + + } + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/follow.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/follow.c:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/follow.c Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,142 ---- + /* the functions in this file take a syntax tree for a regular + expression and produce a DFA using the McNaughton-Yamada + construction. */ + + #include + #include + #include + #include "re.h" + + /* + extern char *strncpy(), *strcat(), *strcpy(); + extern int strlen(); + */ + extern char *strcat(char *s1, const char *s2); + + #define TRUE 1 + /* + extern char *malloc(); + */ + extern Pset pset_union(Pset s1, Pset s2); + extern int pos_cnt; + extern Re_node parse(char *s); + + Re_lit_array lpos; + + + /* extend_re() extends the RE by adding a ".*(" at the front and a "(" + at the back. */ + + char *extend_re(char *s) + { + char *s1; + + s1 = (char *) malloc((unsigned) strlen(s)+4+1); + return (char *) strcat(strcat(strcpy(s1, ".*("), s), ")"); + } + + /* mk_followpos() takes a syntax tree for a regular expression and + traverses it once, computing the followpos function at each node + and returns a pointer to an array whose ith element is a pointer + to a list of position nodes, representing the positions in + followpos(i). */ + + void mk_followpos_1(Re_node e, Pset_array fpos) + { + Pset pos; + int i; + + switch (Op(e)) { + case EOS: break; + case OPSTAR: + pos = Lastpos(e); + while (pos != NULL) { + i = pos->posnum; + (*fpos)[i] = pset_union(Firstpos(e), (*fpos)[i]); + pos = pos->nextpos; + } + mk_followpos_1(Child(e), fpos); + break; + case OPCAT: + pos = Lastpos(Lchild(e)); + while (pos != NULL) { + i = pos->posnum; + (*fpos)[i] = pset_union(Firstpos(Rchild(e)), (*fpos)[i]); + pos = pos->nextpos; + } + mk_followpos_1(Lchild(e), fpos); + mk_followpos_1(Rchild(e), fpos); + break; + case OPOPT: + mk_followpos_1(Child(e), fpos); + break; + case OPALT: + mk_followpos_1(Lchild(e), fpos); + mk_followpos_1(Rchild(e), fpos); + break; + case LITERAL: + break; + default: printf("mk_followpos: unknown node type %d\n", Op(e)); + } + return; + } + + Pset_array mk_followpos(Re_node tree, int npos) + { + int i; + Pset_array fpos; + + if (tree == NULL || npos < 0) return NULL; + fpos = (Pset_array) malloc((unsigned) (npos+1)*sizeof(Pset)); + if (fpos == NULL) return NULL; + for (i = 0; i <= npos; i++) (*fpos)[i] = NULL; + mk_followpos_1(tree, fpos); + return fpos; + } + + /* mk_poslist() sets a static array whose i_th element is a pointer to + the RE-literal at position i. It returns 1 if everything is OK, 0 + otherwise. */ + + /* init performs initialization actions; it returns -1 in case of error, + 0 if everything goes OK. */ + + int init(char *s, int table[32][32]) + { + Pset_array fpos; + Re_node e; + Pset l; + int i, j; + + if ((e = parse(extend_re(s))) == NULL) return -1; + if ((fpos = mk_followpos(e, pos_cnt)) == NULL) return -1; + for (i = 0; i <= pos_cnt; i += 1) { + #ifdef Debug + printf("followpos[%d] = ", i); + #endif + l = (*fpos)[i]; + j = 0; + for ( ; l != NULL; l = l->nextpos) { + #ifdef Debug + printf("%d ", l->posnum); + #endif + table[i][j] = l->posnum; + j++; + } + #ifdef Debug + printf("\n"); + #endif + } + #ifdef Debug + for (i=0; i <= pos_cnt; i += 1) { + j = 0; + while (table[i][j] != 0) { + printf(" %d ", table[i][j]); + j++; + } + printf("\n"); + } + #endif + return (pos_cnt); + } + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/main.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/main.c:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/main.c Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,1050 ---- + /* Copyright (c) 1991 Sun Wu and Udi Manber. All Rights Reserved. */ + #include + #include + #include + #include + #include "agrep.h" + #include "checkfile.h" + #define CHARTYPE unsigned char + + unsigned Mask[MAXSYM]; + unsigned Init1, NO_ERR_MASK, Init[MaxError]; + unsigned Bit[WORD+1]; + CHAR buffer[BlockSize+Maxline+1]; + unsigned Next[MaxNext], Next1[MaxNext]; + unsigned wildmask, endposition, D_endpos; + int REGEX, RE_ERR, FNAME, WHOLELINE, SIMPLEPATTERN; + int COUNT, HEAD, TAIL, LINENUM, INVERSE, I, S, DD, AND, SGREP, JUMP; + int Num_Pat, PSIZE, num_of_matched, SILENT, NOPROMPT, BESTMATCH, NOUPPER; + int NOMATCH, TRUNCATE, FIRST_IN_RE, FIRSTOUTPUT; + int WORDBOUND, DELIMITER, D_length; + int EATFIRST, OUTTAIL; + int FILEOUT; + int DNA = 0; + int APPROX = 0; + int PAT_FILE = 0; + int CONSTANT = 0; + int total_line = 0; /* used in mgrep */ + + CHAR **Textfiles; /* array of filenames to be searched */ + CHAR old_D_pat[MaxDelimit] = "\n"; /* to hold original D_pattern */ + CHAR CurrentFileName[MAXNAME]; + CHAR Progname[MAXNAME]; + CHAR D_pattern[MaxDelimit] = "\n; "; /* string which delimits records -- + defaults to newline */ + int NOFILENAME = 0, /* Boolean flag, set for -h option */ + FILENAMEONLY = 0,/* Boolean flag, set for -l option */ + Numfiles = 0; /* indicates how many files in Textfiles */ + extern int init(char *s, int table[32][32]); + extern void bitap(char old_D_pat[], char *Pattern, int fd, int M, int D); + extern void prepf(int fp); + extern void compat(void); + extern void mgrep(int fd); + extern void sgrep(CHARTYPE *pat, int m, int fd, int D); + extern void preprocess(CHAR *D_pattern, CHAR *Pattern); + extern int maskgen(unsigned char *Pattern, int D); + extern int check_file(char *fname); + + int table[WORD][WORD]; + + void initial_value(void); + void compute_next(int M, unsigned *Next, unsigned *Next1); + int exponen(int m); + void re1(int Text, int M, int D); + void re(int Text, int M, int D); + void r_output(CHAR *buffer, int i, int end, int j); + void file_out(char *fname); + void usage(void); + void checksg(CHAR *Pattern, int D); + void output(register CHAR *buffer, int i1, int i2, int j); + + int main(int argc, char *argv[]) + { + int M, D=0, fp, fd, i; + char c; + int filetype; + unsigned char Pattern[MAXPAT], OldPattern[MAXPAT]; + + initial_value(); + strcpy(Progname, "agrep"); + if (argc < 2) usage(); + Pattern[0] = '\0'; + while(--argc > 0 && (*++argv)[0] == '-') { + c = *(argv[0]+1); + switch(c) { + case 'c' : COUNT = ON; /* output the # of matched */ + break; + case 's' : SILENT = ON; /* silent mode */ + break; + case 'p' : I = 0; /* insertion cost is 0 */ + break; + case 'x' : WHOLELINE = ON; /* match the whole line */ + if(WORDBOUND) { + fprintf(stderr, "%s: illegal option combination\n", Progname); + exit(2); + } + break; + case 'L' : break; + case 'd' : DELIMITER = ON; /* user defines delimiter */ + if(argc <= 1) usage(); + if (argv[0][2] == '\0') {/* space after -d option */ + argv++; + if ((D_length = strlen(argv[0])) > MaxDelimit) { + fprintf(stderr, "%s: delimiter pattern too long\n", Progname); + exit(2); + } + D_pattern[0] = '<'; + strcpy(D_pattern+1, argv[0]); + argc--; + } else { + if ((D_length = strlen(argv[0]+2)) > MaxDelimit) { + fprintf(stderr, "%s: delimiter pattern too long\n", Progname); + exit(2); + } + D_pattern[0] = '<'; + strcpy(D_pattern+1, argv[0]+2); + } /* else */ + strcat(D_pattern, ">; "); + D_length++; /* to count ';' as one */ + break; + case 'e' : argc--; + if(argc == 0) { + fprintf(stderr, "%s: the pattern should immediately follow the -e option\n", Progname); + usage(); + } + if((++argv)[0][0] == '-') { + Pattern[0] = '\\'; + strcat(Pattern, (argv)[0]); + } + else strcat(Pattern, argv[0]); + break; + case 'f' : PAT_FILE = ON; + argv++; + argc--; + if((fp = open(argv[0], 0)) < 0) { + fprintf(stderr, "%s: Can't open pattern file %s\n", Progname, argv[0]); + exit(2); + } + break; + case 'h' : NOFILENAME = ON; + break; + case 'i' : NOUPPER = ON; + break; + case 'k' : argc--; + if(argc == 0) { + fprintf(stderr, "%s: the pattern should immediately follow the -k option\n", Progname); + usage(); + } + CONSTANT = ON; + argv++; + strcat(Pattern, argv[0]); + if(argc > 1 && argv[1][0] == '-') { + fprintf(stderr, "%s: -k should be the last option in the command\n", Progname); + exit(2); + } + break; + case 'l' : FILENAMEONLY = ON; + break; + case 'n' : LINENUM = ON; /* output prefixed by line no*/ + break; + case 'v' : INVERSE = ON; /* output no-matched lines */ + break; + case 't' : OUTTAIL = ON; /* output from tail of delimiter */ + break; + case 'B' : BESTMATCH = ON; + break; + case 'w' : WORDBOUND = ON;/* match to words */ + if(WHOLELINE) { + fprintf(stderr, "%s: illegal option combination\n", Progname); + exit(2); + } + break; + case 'y' : NOPROMPT = ON; + break; + case 'I' : I = atoi(argv[0]+2); /* Insertion Cost */ + JUMP = ON; + break; + case 'S' : S = atoi(argv[0]+2); /* Substitution Cost */ + JUMP = ON; + break; + case 'D' : DD = atoi(argv[0]+2); /* Deletion Cost */ + JUMP = ON; + break; + case 'G' : FILEOUT = ON; + COUNT = ON; + break; + default : if (isdigit(c)) { + APPROX = ON; + D = atoi(argv[0]+1); + if (D > MaxError) { + fprintf(stderr,"%s: the maximum number of errors is %d \n", Progname, MaxError); + exit(2); + } + } else { + fprintf(stderr, "%s: illegal option -%c\n",Progname, c); + usage(); + } + } /* switch(c) */ + } /* while (--argc > 0 && (*++argv)[0] == '-') */ + + if (FILENAMEONLY && NOFILENAME) { + fprintf(stderr, "%s: -h and -l options are mutually exclusive\n",Progname); + } + if (COUNT && (FILENAMEONLY || NOFILENAME)) { + FILENAMEONLY = OFF; + if(!FILEOUT) NOFILENAME = OFF; + } + if (!(PAT_FILE) && Pattern[0] == '\0') { /* Pattern not set with -e option */ + if (argc == 0) usage(); + strcpy(Pattern, *argv); + argc--; + argv++; + } + Numfiles = 0; + fd = 3; /* make sure it's not 0 */ + if (argc == 0) /* check Pattern against stdin */ + fd = 0; + else { + if (!(Textfiles = (CHAR **)malloc(argc * sizeof(CHAR *) ))) { + fprintf(stderr, "%s: malloc failure (you probably don't have enough memory)\n", Progname); + exit(2); + } + while (argc--) { /* one or more filenames on command line -- put + the valid filenames in a array of strings */ + /* + if ((filetype = check_file(*argv)) != ISASCIIFILE) { + if(filetype == NOSUCHFILE) fprintf(stderr,"%s: %s: no such file or directory\n",Progname,*argv); + argv++; + */ + + if ((filetype = check_file(*argv)) == NOSUCHFILE) { + if(filetype == NOSUCHFILE) fprintf(stderr,"%s: %s: no such file or directory\n",Progname,*argv); + argv++; + } else { /* file is ascii*/ + if (!(Textfiles[Numfiles] = (CHAR *)malloc((strlen(*argv)+1)))) { + fprintf(stderr, "%s: malloc failure (you probably don't have enough memory)\n", Progname); + exit(2); + } + strcpy(Textfiles[Numfiles++], *argv++); + } /* else */ + } /* while (argc--) */ + } /* else */ + checksg(Pattern, D); /* check if the pattern is simple */ + strcpy(OldPattern, Pattern); + if (SGREP == 0) { + preprocess(D_pattern, Pattern); + strcpy(old_D_pat, D_pattern); + M = maskgen(Pattern, D); + } + else M = strlen(OldPattern); + if (PAT_FILE) prepf(fp); + if (Numfiles > 1) FNAME = ON; + if (NOFILENAME) FNAME = 0; + num_of_matched = 0; + compat(); /* check compatibility between options */ + if (fd == 0) { + if(FILENAMEONLY) { + fprintf(stderr, "%s: -l option is not compatible with standard input\n", Progname); + exit(2); + } + if(PAT_FILE) mgrep(fd); + else { + if(SGREP) sgrep(OldPattern, strlen(OldPattern), fd, D); + else bitap(old_D_pat, Pattern, fd, M, D); + } + if (COUNT) { + if(INVERSE && PAT_FILE) printf("%d\n", total_line-num_of_matched); + else printf("%d\n", num_of_matched); + } + } + else { + for (i = 0; i < Numfiles; i++, close(fd), num_of_matched = 0) { + strcpy(CurrentFileName, Textfiles[i]); + if ((fd = open(Textfiles[i], 0)) <= 0) { + fprintf(stderr, "%s: can't open file %s\n",Progname, Textfiles[i]); + } + else { + if(PAT_FILE) mgrep(fd); + else { + if(SGREP) sgrep(OldPattern, strlen(OldPattern), fd, D); + else bitap(old_D_pat, Pattern, fd, M, D); + } + if (num_of_matched) NOMATCH = OFF; + if (COUNT && !FILEOUT) { + if(INVERSE && PAT_FILE) { + if(FNAME) printf("%s: %d\n", CurrentFileName, total_line - num_of_matched); + else printf("%d\n", total_line - num_of_matched); + } + else { + if(FNAME) printf("%s: %d\n", CurrentFileName, num_of_matched); + else printf("%d\n", num_of_matched); + } + } /* if COUNT */ + if(FILEOUT && num_of_matched) { + file_out(CurrentFileName); + } + } /* else */ + } /* for i < Numfiles */ + if(NOMATCH && BESTMATCH) { + if(WORDBOUND || WHOLELINE || LINENUM || INVERSE) { + SGREP = 0; + preprocess(D_pattern, Pattern); + strcpy(old_D_pat, D_pattern); + M = maskgen(Pattern, D); + } + COUNT=ON; D=1; + while(D 0) { + if(PAT_FILE) mgrep(fd); + else { + if(SGREP) sgrep(OldPattern,strlen(OldPattern),fd,D); + else bitap(old_D_pat,Pattern,fd,M,D); + } + } + } /* for i < Numfiles */ + D++; + } /* while */ + if(num_of_matched > 0) { + D--; COUNT = 0; + if(NOPROMPT) goto GO_AHEAD; + if(D==1) fprintf(stderr, "best match has 1 error, "); + else fprintf(stderr, "best match has %d errors, ", D); + fflush(stderr); + if(num_of_matched == 1) fprintf(stderr,"there is 1 match, output it? (y/n)"); + else fprintf(stderr,"there are %d matches, output them? (y/n)", num_of_matched); + scanf("%c",&c); + if(c != 'y') goto CONT; + GO_AHEAD: + for (i = 0; i < Numfiles; i++, close(fd)) { + strcpy(CurrentFileName, Textfiles[i]); + if ((fd = open(Textfiles[i], 0)) > 0) { + if(PAT_FILE) mgrep(fd); + else { + if(SGREP) sgrep(OldPattern,strlen(OldPattern),fd,D); + else bitap(old_D_pat,Pattern,fd,M,D); + } + } + } /* for i < Numfiles */ + NOMATCH = 0; + } + } + } + CONT: + if(EATFIRST) { + printf("\n"); + EATFIRST = OFF; + } + if(num_of_matched) NOMATCH = OFF; + if(NOMATCH) exit(1); + exit(0); + } /* end of main() */ + + void initial_value(void) + { + int i; + + JUMP = REGEX = FNAME = BESTMATCH = NOPROMPT = NOUPPER = 0; + COUNT = LINENUM = WHOLELINE = SGREP = 0; + EATFIRST = INVERSE = AND = TRUNCATE = OUTTAIL = 0; + FIRST_IN_RE = NOMATCH = FIRSTOUTPUT = ON; + I = DD = S = 1; + HEAD = TAIL = ON; + D_length = 2; + SILENT = Num_Pat = PSIZE = SIMPLEPATTERN = num_of_matched = 0 ; + WORDBOUND = DELIMITER = RE_ERR = 0; + Bit[WORD] = 1; + for (i = WORD - 1; i > 0 ; i--) Bit[i] = Bit[i+1] << 1; + for (i=0; i< MAXSYM; i++) Mask[i] = 0; + } + + void compute_next(int M, unsigned *Next, unsigned *Next1) + { + int i, j=0, n, k, temp; + int mid, pp; + int MM, base; + unsigned V[WORD]; + + base = WORD - M; + temp = Bit[base]; Bit[base] = 0; + for (i=0; i 0 && j < 10) { + V[i] = V[i] | Bit[base + table[i][j++]]; + } + } + Bit[base]=temp; + if(M <= SHORTREG) + { + k = exponen(M); + pp = 2*k; + for(i=k; i>1); + for(j=M; j>=1; j--) + { + if(n & Bit[WORD]) Next[i] = Next[i] | V[j]; + n = (n>>1); + } + } + return; + } + if(M > MAXREG) fprintf(stderr, "%s: regular expression too long\n", Progname); + MM = M; + if(M & 1) M=M+1; + k = exponen(M/2); + pp = 2*k; + mid = MM/2; + for(i=k; i>1); + for(j=MM; j>mid ; j--) + { + if(n & Bit[WORD]) Next[i] = Next[i] | V[j-mid]; + n = (n>>1); + } + n=i-k; + Next1[i-k] = 0; + for(j = 0; j>1); + } + } + return; + } + + int exponen(int m) + { int i, ex; + ex= 1; + for (i=0; i 30) { + fprintf(stderr, "%s: regular expression too long\n", Progname); + exit(2); + } + base = WORD - M; + hh = M/2; + for(i=WORD, j=0; j < hh ; i--, j++) LL = LL | Bit[i]; + if(FIRST_IN_RE) compute_next(M, Next, Next1); + /*SUN: try: change to memory allocation */ + FIRST_IN_RE = 0; + Newline = '\n'; + Init[0] = Bit[base]; + if(HEAD) Init[0] = Init[0] | Bit[base+1]; + for(i=1; i<= D; i++) Init[i] = Init[i-1] | Next[Init[i-1]>>hh] | Next1[Init[i-1]&LL]; + Init1 = Init[0] | 1; + Init0 = Init[0]; + r2 = r3 = Init[0]; + for(k=0; k<= D; k++) { A[k] = B[k] = Init[k]; } + if ( D == 0 ) + { + while ((num_read = read(Text, buffer + Maxline, BlockSize)) > 0) + { + i=Maxline; end = num_read + Maxline; + if((num_read < BlockSize) && buffer[end-1] != '\n') buffer[end] = '\n'; + if(FIRST_LOOP) { /* if first time in the loop add a newline */ + buffer[i-1] = '\n'; /* in front the text. */ + i--; + FIRST_LOOP = 0; + } + while ( i < end ) + { + c = buffer[i++]; + CMask = Mask[c]; + if(c != Newline) + { if(CMask != 0) { + r1 = Init1 & r3; + r2 = ((Next[r3>>hh] | Next1[r3&LL]) & CMask) | r1; + } + else { + r2 = r3 & Init1; + } + } + else { j++; + r1 = Init1 & r3; /* match against endofline */ + r2 = ((Next[r3>>hh] | Next1[r3&LL]) & CMask) | r1; + if(TAIL) r2 = (Next[r2>>hh] | Next1[r2&LL]) | r2; /* epsilon move */ + if(( r2 & 1 ) ^ INVERSE) { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; + } + r_output(buffer, i-1, end, j); + } + r3 = Init0; + r2 = (Next[r3>>hh] | Next1[r3&LL]) & CMask | Init0; + /* match begin of line */ + } + c = buffer[i++]; + CMask = Mask[c]; + if(c != Newline) + { if(CMask != 0) { + r1 = Init1 & r2; + r3 = ((Next[r2>>hh] | Next1[r2&LL]) & CMask) | r1; + } + else r3 = r2 & Init1; + } /* if(NOT Newline) */ + else { j++; + r1 = Init1 & r2; /* match against endofline */ + r3 = ((Next[r2>>hh] | Next1[r2&LL]) & CMask) | r1; + if(TAIL) r3 = ( Next[r3>>hh] | Next1[r3&LL] ) | r3; + /* epsilon move */ + if(( r3 & 1 ) ^ INVERSE) { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; + } + r_output(buffer, i-1, end, j); + } + r2 = Init0; + r3 = ((Next[r2>>hh] | Next1[r2&LL]) & CMask) | Init0; + /* match begin of line */ + } + } /* while i < end ... */ + strncpy(buffer, buffer+num_read, Maxline); + } /* end while read()... */ + return; + } /* end if (D == 0) */ + while ((num_read = read(Text, buffer + Maxline, BlockSize)) > 0) + { + i=Maxline; end = Maxline + num_read; + if((num_read < BlockSize) && buffer[end-1] != '\n') buffer[end] = '\n'; + if(FIRST_TIME) { /* if first time in the loop add a newline */ + buffer[i-1] = '\n'; /* in front the text. */ + i--; + FIRST_TIME = 0; + } + while (i < end ) + { + c = buffer[i]; + CMask = Mask[c]; + if(c != Newline) + { + if(CMask != 0) { + r2 = B[0]; + r1 = Init1 & r2; + A[0] = ((Next[r2>>hh] | Next1[r2&LL]) & CMask) | r1; + r3 = B[1]; + r1 = Init1 & r3; + r0 = r2 | A[0]; /* A[0] | B[0] */ + A[1] = ((Next[r3>>hh] | Next1[r3&LL]) & CMask) | (( r2 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 1) goto Nextchar; + r2 = B[2]; + r1 = Init1 & r2; + r0 = r3 | A[1]; + A[2] = ((Next[r2>>hh] | Next1[r2&LL]) & CMask) | ((r3 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 2) goto Nextchar; + r3 = B[3]; + r1 = Init1 & r3; + r0 = r2 | A[2]; + A[3] = ((Next[r3>>hh] | Next1[r3&LL]) & CMask) | ((r2 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 3) goto Nextchar; + r2 = B[4]; + r1 = Init1 & r2; + r0 = r3 | A[3]; + A[4] = ((Next[r2>>hh] | Next1[r2&LL]) & CMask) | ((r3 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 4) goto Nextchar; + } /* if(CMask) */ + else { + r2 = B[0]; + A[0] = r2 & Init1; + r3 = B[1]; + r1 = Init1 & r3; + r0 = r2 | A[0]; + A[1] = ((r2 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 1) goto Nextchar; + r2 = B[2]; + r1 = Init1 & r2; + r0 = r3 | A[1]; + A[2] = ((r3 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 2) goto Nextchar; + r3 = B[3]; + r1 = Init1 & r3; + r0 = r2 | A[2]; + A[3] = ((r2 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 3) goto Nextchar; + r2 = B[4]; + r1 = Init1 & r2; + r0 = r3 | A[3]; + A[4] = ((r3 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 4) goto Nextchar; + } + } + else { j++; + r1 = Init1 & B[D]; /* match against endofline */ + A[D] = ((Next[B[D]>>hh] | Next1[B[D]&LL]) & CMask) | r1; + if(TAIL) A[D] = ( Next[A[D]>>hh] | Next1[A[D]&LL] ) | A[D]; + /* epsilon move */ + if(( A[D] & 1 ) ^ INVERSE) { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; + } + r_output(buffer, i, end, j); + } + for(k=0; k<=D; k++) B[k] = Init[0]; + r1 = Init1 & B[0]; + A[0] = (( Next[B[0]>>hh] | Next1[B[0]&LL]) & CMask) | r1; + for(k=1; k<=D; k++) { + r3 = B[k]; + r1 = Init1 & r3; + r2 = A[k-1] | B[k-1]; + A[k] = ((Next[r3>>hh] | Next1[r3&LL]) & CMask) | ((B[k-1] | Next[r2>>hh] | Next1[r2&LL]) & r_NO_ERR) | r1; + } + } + Nextchar: i=i+1; + c = buffer[i]; + CMask = Mask[c]; + if(c != Newline) + { + if(CMask != 0) { + r2 = A[0]; + r1 = Init1 & r2; + B[0] = ((Next[r2>>hh] | Next1[r2&LL]) & CMask) | r1; + r3 = A[1]; + r1 = Init1 & r3; + r0 = B[0] | r2; + B[1] = ((Next[r3>>hh] | Next1[r3&LL]) & CMask) | ((r2 | Next[r0>>hh] | Next1[r0&LL]) & r_NO_ERR) | r1 ; + if(D == 1) goto Nextchar1; + r2 = A[2]; + r1 = Init1 & r2; + r0 = B[1] | r3; + B[2] = ((Next[r2>>hh] | Next1[r2&LL]) & CMask) | ((r3 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 2) goto Nextchar1; + r3 = A[3]; + r1 = Init1 & r3; + r0 = B[2] | r2; + B[3] = ((Next[r3>>hh] | Next1[r3&LL]) & CMask) | ((r2 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 3) goto Nextchar1; + r2 = A[4]; + r1 = Init1 & r2; + r0 = B[3] | r3; + B[4] = ((Next[r2>>hh] | Next1[r2&LL]) & CMask) | ((r3 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 4) goto Nextchar1; + } /* if(CMask) */ + else { + r2 = A[0]; + B[0] = r2 & Init1; + r3 = A[1]; + r1 = Init1 & r3; + r0 = B[0] | r2; + B[1] = ((r2 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 1) goto Nextchar1; + r2 = A[2]; + r1 = Init1 & r2; + r0 = B[1] | r3; + B[2] = ((r3 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 2) goto Nextchar1; + r3 = A[3]; + r1 = Init1 & r3; + r0 = B[2] | r2; + B[3] = ((r2 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 3) goto Nextchar1; + r2 = A[4]; + r1 = Init1 & r2; + r0 = B[3] | r3; + B[4] = ((r3 | Next[r0>>hh] | Next1[r0&LL])&r_NO_ERR) | r1 ; + if(D == 4) goto Nextchar1; + } + } /* if(NOT Newline) */ + else { j++; + r1 = Init1 & A[D]; /* match against endofline */ + B[D] = ((Next[A[D]>>hh] | Next1[A[D]&LL]) & CMask) | r1; + if(TAIL) B[D] = ( Next[B[D]>>hh] | Next1[B[D]&LL] ) | B[D]; + /* epsilon move */ + if(( B[D] & 1 ) ^ INVERSE) { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; + } + r_output(buffer, i, end, j); + } + for(k=0; k<=D; k++) A[k] = Init0; + r1 = Init1 & A[0]; + B[0] = ((Next[A[0]>>hh] | Next1[A[0]&LL]) & CMask) | r1; + for(k=1; k<=D; k++) { + r3 = A[k]; + r1 = Init1 & r3; + r2 = A[k-1] | B[k-1]; + B[k] = ((Next[r3>>hh] | Next1[r3&LL]) & CMask) | ((A[k-1] | Next[r2>>hh] | Next1[r2&LL]) & r_NO_ERR) | r1; + } + } + Nextchar1: i=i+1; + } /* while */ + strncpy(buffer, buffer+num_read, Maxline); + } /* while */ + return; + } /* re1 */ + + void re(int Text, int M, int D) + { + register unsigned i, c, r1, r2, r3, CMask, k, Newline, Init0, Init1, end; + register unsigned r_even, r_odd, r_NO_ERR ; + unsigned RMask[MAXSYM]; + unsigned A[MaxRerror+1], B[MaxRerror+1]; + int num_read, j=0, lasti, base, ResidueSize; + int FIRST_TIME; /* Flag */ + base = WORD - M; + k = 2*exponen(M); + if(FIRST_IN_RE) { + compute_next(M, Next, Next1); + FIRST_IN_RE = 0; } + for(i=0; i< MAXSYM; i++) RMask[i] = Mask[i]; + r_NO_ERR = NO_ERR_MASK; + Newline = '\n'; + lasti = Maxline; + Init0 = Init[0] = Bit[base]; + if(HEAD) Init0 = Init[0] = Init0 | Bit[base+1] ; + for(i=1; i<= D; i++) Init[i] = Init[i-1] | Next[Init[i-1]]; /* can be out? */ + Init1 = Init0 | 1; + r2 = r3 = Init0; + for(k=0; k<= D; k++) { A[k] = B[k] = Init[0]; } /* can be out? */ + FIRST_TIME = ON; + if ( D == 0 ) + { + while ((num_read = read(Text, buffer + Maxline, BlockSize)) > 0) + { + i=Maxline; end = Maxline + num_read ; + if((num_read < BlockSize)&&buffer[end-1] != '\n') buffer[end] = '\n'; + if(FIRST_TIME) { + buffer[i-1] = '\n'; + i--; + FIRST_TIME = 0; + } + while (i < end) + { + c = buffer[i++]; + CMask = RMask[c]; + if(c != Newline) + { + r1 = Init1 & r3; + r2 = (Next[r3] & CMask) | r1; + } + else { + r1 = Init1 & r3; /* match against '\n' */ + r2 = Next[r3] & CMask | r1; + j++; + if(TAIL) r2 = Next[r2] | r2 ; /* epsilon move */ + if(( r2 & 1) ^ INVERSE) { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; + } + r_output(buffer, i-1, end, j); + } + lasti = i - 1; + r3 = Init0; + r2 = (Next[r3] & CMask) | Init0; + } + c = buffer[i++]; + CMask = RMask[c]; + if(c != Newline) + { + r1 = Init1 & r2; + r3 = (Next[r2] & CMask) | r1; + } + else { j++; + r1 = Init1 & r2; /* match against endofline */ + r3 = Next[r2] & CMask | r1; + if(TAIL) r3 = Next[r3] | r3; + if(( r3 & 1) ^ INVERSE) { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; + } + r_output(buffer, i-1, end, j); + } + lasti = i - 1; + r2 = Init0; + r3 = (Next[r2] & CMask) | Init0; /* match the newline */ + } + } /* while */ + ResidueSize = Maxline + num_read - lasti; + if(ResidueSize > Maxline) { + ResidueSize = Maxline; } + strncpy(buffer+Maxline-ResidueSize, buffer+lasti, ResidueSize); + lasti = Maxline - ResidueSize; + } /* while */ + return; + } /* end if(D==0) */ + while ((num_read = read(Text, buffer + Maxline, BlockSize)) > 0) + { + i=Maxline; end = Maxline+num_read; + if((num_read < BlockSize) && buffer[end-1] != '\n') buffer[end] = '\n'; + if(FIRST_TIME) { + buffer[i-1] = '\n'; + i--; + FIRST_TIME = 0; + } + while (i < end) + { c = buffer[i++]; + CMask = RMask[c]; + if (c != Newline) + { + r_even = B[0]; + r1 = Init1 & r_even; + A[0] = (Next[r_even] & CMask) | r1; + r_odd = B[1]; + r1 = Init1 & r_odd; + r2 = (r_even | Next[r_even|A[0]]) &r_NO_ERR; + A[1] = (Next[r_odd] & CMask) | r2 | r1 ; + if(D == 1) goto Nextchar; + r_even = B[2]; + r1 = Init1 & r_even; + r2 = (r_odd | Next[r_odd|A[1]]) &r_NO_ERR; + A[2] = (Next[r_even] & CMask) | r2 | r1 ; + if(D == 2) goto Nextchar; + r_odd = B[3]; + r1 = Init1 & r_odd; + r2 = (r_even | Next[r_even|A[2]]) &r_NO_ERR; + A[3] = (Next[r_odd] & CMask) | r2 | r1 ; + if(D == 3) goto Nextchar; + r_even = B[4]; + r1 = Init1 & r_even; + r2 = (r_odd | Next[r_odd|A[3]]) &r_NO_ERR; + A[4] = (Next[r_even] & CMask) | r2 | r1 ; + goto Nextchar; + } /* if NOT Newline */ + else { j++; + r1 = Init1 & B[D]; /* match endofline */ + A[D] = (Next[B[D]] & CMask) | r1; + if(TAIL) A[D] = Next[A[D]] | A[D]; + if((A[D] & 1) ^ INVERSE ) { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; + } + r_output(buffer, i-1, end, j); + } + for(k=0; k<= D; k++) { A[k] = B[k] = Init[k]; } + r1 = Init1 & B[0]; + A[0] = (Next[B[0]] & CMask) | r1; + for(k=1; k<= D; k++) { + r1 = Init1 & B[k]; + r2 = (B[k-1] | Next[A[k-1]|B[k-1]]) &r_NO_ERR; + A[k] = (Next[B[k]] & CMask) | r1 | r2; + } + } + Nextchar: + c = buffer[i]; + CMask = RMask[c]; + if(c != Newline) + { + r1 = Init1 & A[0]; + B[0] = (Next[A[0]] & CMask) | r1; + r1 = Init1 & A[1]; + B[1] = (Next[A[1]] & CMask) | ((A[0] | Next[A[0] | B[0]]) & r_NO_ERR) | r1 ; + if(D == 1) goto Nextchar1; + r1 = Init1 & A[2]; + B[2] = (Next[A[2]] & CMask) | ((A[1] | Next[A[1] | B[1]]) &r_NO_ERR) | r1 ; + if(D == 2) goto Nextchar1; + r1 = Init1 & A[3]; + B[3] = (Next[A[3]] & CMask) | ((A[2] | Next[A[2] | B[2]])&r_NO_ERR) | r1 ; + if(D == 3) goto Nextchar1; + r1 = Init1 & A[4]; + B[4] = (Next[A[4]] & CMask) | ((A[3] | Next[A[3] | B[3]])&r_NO_ERR) | r1 ; + goto Nextchar1; + } /* if(NOT Newline) */ + else { j++; + r1 = Init1 & A[D]; /* match endofline */ + B[D] = (Next[A[D]] & CMask) | r1; + if(TAIL) B[D] = Next[B[D]] | B[D]; + if((B[D] & 1) ^ INVERSE ) { + if(FILENAMEONLY) { + num_of_matched++; + printf("%s\n", CurrentFileName); + return; + } + r_output(buffer, i, end, j); + } + for(k=0; k<= D; k++) { A[k] = B[k] = Init[k]; } + r1 = Init1 & A[0]; + B[0] = (Next[A[0]] & CMask) | r1; + for(k=1; k<= D; k++) { + r1 = Init1 & A[k]; + r2 = (A[k-1] | Next[A[k-1]|B[k-1]])&r_NO_ERR; + B[k] = (Next[A[k]] & CMask) | r1 | r2; + } + } + Nextchar1: i++; + } /* while i < end */ + strncpy(buffer, buffer+num_read, Maxline); + } /* while read() */ + return; + } /* re */ + + + void r_output(CHAR *buffer, int i, int end, int j) + { + int bp; + if(i >= end) return; + num_of_matched++; + if(COUNT) return; + if(FNAME) printf("%s: ", CurrentFileName); + bp = i-1; + while ((buffer[bp] != '\n') && (bp > 0)) bp--; + if(LINENUM) printf("%d: ", j); + if(buffer[bp] != '\n') bp = Maxline-1; + bp++; + while (bp <= i ) putchar(buffer[bp++]); + } + + void file_out(char *fname) + { + int num_read; + int fd; + int i, len; + CHAR buf[4097]; + if(FNAME) { + len = strlen(fname); + putchar('\n'); + for(i=0; i< len; i++) putchar(':'); + putchar('\n'); + printf("%s\n", CurrentFileName); + len = strlen(fname); + for(i=0; i< len; i++) putchar(':'); + putchar('\n'); + fflush(stdout); + } + fd = open(fname, 0); + while((num_read = read(fd, buf, 4096)) > 0) + write(1, buf, num_read); + } + + + void usage(void) + { + fprintf(stderr, "usage: %s [-#cdehiklnpstvwxBDGIS] [-f patternfile] pattern [files]\n", Progname); + printf("\n"); + fprintf(stderr, "summary of frequently used options:\n"); + fprintf(stderr, "-#: find matches with at most # errors\n"); + fprintf(stderr, "-c: output the number of matched records\n"); + fprintf(stderr, "-d: define record delimiter\n"); + fprintf(stderr, "-h: do not output file names\n"); + fprintf(stderr, "-i: case-insensitive search, e.g., 'a' = 'A'\n"); + fprintf(stderr, "-l: output the names of files that contain a match\n"); + fprintf(stderr, "-n: output record prefixed by record number\n"); + fprintf(stderr, "-v: output those records containing no matches\n"); + fprintf(stderr, "-w: pattern has to match as a word, e.g., 'win' will not match 'wind'\n"); + fprintf(stderr, "-B: best match mode. find the closest matches to the pattern\n"); + fprintf(stderr, "-G: output the files that contain a match\n"); + printf("\n"); + + exit(2); + } + + void checksg(CHAR *Pattern, int D) + { + char c; + int i, m; + m = strlen(Pattern); + if(!(PAT_FILE) && m <= D) { + fprintf(stderr, "%s: size of pattern must be greater than number of errors\n", Progname); + exit(2); + } + SIMPLEPATTERN = ON; + for (i=0; i < m; i++) + { + switch(Pattern[i]) + { + case ';' : SIMPLEPATTERN = OFF; break; + case ',' : SIMPLEPATTERN = OFF; break; + case '.' : SIMPLEPATTERN = OFF; break; + case '*' : SIMPLEPATTERN = OFF; break; + case '-' : SIMPLEPATTERN = OFF; break; + case '[' : SIMPLEPATTERN = OFF; break; + case ']' : SIMPLEPATTERN = OFF; break; + case '(' : SIMPLEPATTERN = OFF; break; + case ')' : SIMPLEPATTERN = OFF; break; + case '<' : SIMPLEPATTERN = OFF; break; + case '>' : SIMPLEPATTERN = OFF; break; + case '^' : if(D > 0) SIMPLEPATTERN = OFF; + break; + case '$' : if(D > 0) SIMPLEPATTERN = OFF; + break; + case '|' : SIMPLEPATTERN = OFF; break; + case '#' : SIMPLEPATTERN = OFF; break; + case '\\' : SIMPLEPATTERN = OFF; break; + default : break; + } + } + if (CONSTANT) SIMPLEPATTERN = ON; + if (SIMPLEPATTERN == OFF) return; + if (NOUPPER && D) return; + if (JUMP == ON) return; + if (I == 0) return; + if (LINENUM) return; + if (DELIMITER) return; + if (INVERSE) return; + if (WORDBOUND && D > 0) return; + if (WHOLELINE && D > 0) return; + if (SILENT) return; /* REMINDER: to be removed */ + SGREP = ON; + if(m >= 16) DNA = ON; + for(i=0; i i2) return; + num_of_matched++; + if(COUNT) return; + if(SILENT) return; + if(OUTTAIL) { + i1 = i1 + D_length; + i2 = i2 + D_length; + } + if(DELIMITER) j = j+1; + if(FIRSTOUTPUT) { + if (buffer[i1] == '\n') { + i1++; + EATFIRST = ON; + } + FIRSTOUTPUT = 0; + } + if(TRUNCATE) { + fprintf(stderr, "WARNING!!! some lines have been truncated in output record #%d\n", num_of_matched-1); + } + while(buffer[i1] == '\n' && i1 <= i2) { + printf("\n"); + i1++; + } + if(FNAME == ON) printf("%s: ", CurrentFileName); + if(LINENUM) printf("%d: ", j-1); + bp = buffer + i1; + outend = buffer + i2; + while(bp <= outend) putchar(*bp++); + } + + /* end of main.c */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/maskgen.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/maskgen.c:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/maskgen.c Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,167 ---- + /* Copyright (c) 1991 Sun Wu and Udi Manber. All Rights Reserved. */ + #include "agrep.h" + + extern unsigned D_endpos, endposition, Init1, wildmask; + extern Mask[], Bit[], Init[], NO_ERR_MASK; + extern int AND, SIMPLEPATTERN, REGEX, NOUPPER, D_length; + extern unsigned char Progname[]; + + int maskgen(unsigned char *Pattern, int D) + { + struct term { int flag; unsigned char class1[WORD]; + } position[WORD+10]; + unsigned char c; + + int i, j, k, l, M, OR=0, EVEN = 0, base, No_error; + + + for(i=0; i'\n", Progname); + exit(2); + } + break; + case LRANGE : if(No_error == ON) NO_ERR_MASK = NO_ERR_MASK | Bit[j]; + i=i+1; + if (Pattern[i] == NOTSYM) { position[j].flag = Compl; i++; } + k=0; + while (Pattern[i] != RRANGE && i < M) + { + if(Pattern[i] == HYPHEN) + { position[j].class1[k-1] = Pattern[i+1]; i=i+2; } + else { + position[j].class1[k] = position[j].class1[k+1] = Pattern[i]; + k = k+2; i++; + } + } + if(i == M) { + fprintf(stderr, "%s: illegal pattern, unmatched '[', ']'\n",Progname); + exit(2); + } + position[j].class1[k] = '\0'; + j++; break; + case RRANGE : fprintf(stderr, "%s: illegal pattern, unmatched '[', ']'\n", Progname); + exit(2); + break; + case ORPAT : if(REGEX == ON || AND == ON) { + fprintf(stderr, "illegal pattern \n"); + exit(2); + } + OR = ON; + position[j].flag = 2; position[j].class1[0] = '\0'; + endposition = endposition | Bit[j++]; break; + case ANDPAT : position[j].flag = 2; position[j].class1[0] = '\0'; + if(j > D_length) AND = ON; + if(OR || (REGEX == ON && j>D_length)) { + fprintf(stderr, "illegal pattern \n"); + exit(2); + } + endposition = endposition | Bit[j++]; break; + /* + case ' ' : if (Pattern[i-1] == ORPAT || Pattern[i-1] == ANDPAT) break; + if(No_error == ON) NO_ERR_MASK = NO_ERR_MASK | Bit[j]; + position[j].flag = 0; + position[j].class1[0] = position[j].class1[1] = Pattern[i]; + position[j++].class1[2] = '\0'; break; + */ + case '\n' : NO_ERR_MASK = NO_ERR_MASK | Bit[j]; + position[j].class1[0] = position[j].class1[1] = '\n'; + position[j++].class1[2] = '\0'; + break; + case WORDB : NO_ERR_MASK = NO_ERR_MASK | Bit[j]; + position[j].class1[0] = 1; + position[j].class1[1] = 47; + position[j].class1[2] = 58; + position[j].class1[3] = 64; + position[j].class1[4] = 91; + position[j].class1[5] = 96; + position[j].class1[6] = 123; + position[j].class1[7] = 127; + position[j++].class1[8] = '\0'; + break; + case NNLINE : NO_ERR_MASK |= Bit[j]; + position[j].class1[0] = position[j].class1[1] = '\n'; + position[j].class1[2] = position[j].class1[3] = NNLINE; + position[j++].class1[4] = '\0'; + break; + default : if(No_error == ON) NO_ERR_MASK = NO_ERR_MASK | Bit[j]; + position[j].flag = 0; + position[j].class1[0] = position[j].class1[1] = Pattern[i]; + position[j++].class1[2] = '\0'; + } + if(j > WORD) { + fprintf(stderr, "%s: pattern too long\n", Progname); + exit(2); + } + } + if (EVEN != 0) { + fprintf(stderr, "%s: illegal pattern, unmatched '<', '>'\n", Progname); + exit(2); + } + M = j - 1; + base = WORD - M; + wildmask = (wildmask >> base); + endposition = (endposition >> base); + NO_ERR_MASK = (NO_ERR_MASK >> 1) & (~Bit[1]); + NO_ERR_MASK = ~NO_ERR_MASK >> (base-1); + for (i=1; i<= WORD - M ; i++) Init[0] = Init[0] | Bit[i]; + Init[0] = Init[0] | endposition; + /* not necessary for INit[i], i>0, */ + /* but at every begining of the matching process append one + no-match character to initialize the error vectors */ + endposition = ( endposition << 1 ) + 1; + Init1 = (Init[0] | wildmask | endposition) ; + D_endpos = ( endposition >> ( M - D_length ) ) << ( M - D_length); + endposition = endposition ^ D_endpos; + #ifdef DEBUG + printf("endposition: %o\n", endposition); + printf("no_err_mask: %o\n", NO_ERR_MASK); + #endif + for(c=0, i=0; i < MAXSYM; c++, i++) + { + for (k=1, l=0; k<=M ; k++, l=0) { + while (position[k].class1[l] != '\0') { + if (position[k].class1[l] == NOCARE && (c != '\n' || REGEX) ) + { Mask[c] = Mask[c] | Bit[base + k]; break; } + if (c >= position[k].class1[l] && c <= position[k].class1[l+1]) + { Mask[c] = Mask[c] | Bit[base + k]; break; } + l = l + 2; } + if (position[k].flag == Compl) Mask[c] = Mask[c] ^ Bit[base+k]; + } + } + if(NOUPPER) for(c='A'; c<='Z'; c=c+1) if (isupper(c)) + Mask[c] = Mask[tolower(c)]; + return(M); + } + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/mgrep.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/mgrep.c:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/mgrep.c Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,321 ---- + /* Copyright (c) 1991 Sun Wu and Udi Manber. All Rights Reserved. */ + /* multipattern matcher */ + #include + #include + #include + #include + #define MAXPAT 256 + #define MAXLINE 1024 + #define MAXSYM 256 + #define MAXMEMBER1 4096 + #define MAXPATFILE 260000 + #define BLOCKSIZE 8192 + #define MAXHASH 8192 + #define mm 8191 + #define max_num 30000 + #define W_DELIM 128 + #define L_DELIM 10 + + extern COUNT, FNAME, SILENT, FILENAMEONLY, num_of_matched; + extern INVERSE; + extern WORDBOUND, WHOLELINE, NOUPPER; + extern unsigned char CurrentFileName[], Progname[]; + extern total_line; + + int LONG = 0; + int SHORT = 0; + int p_size=0; + unsigned char SHIFT1[MAXMEMBER1]; + unsigned char tr[MAXSYM]; + unsigned char tr1[MAXSYM]; + struct pat_list { + int index; + struct pat_list *next; + } *HASH[MAXHASH]; + struct pat_list *pt, *qt; + unsigned char buf[MAXPATFILE+BLOCKSIZE]; + unsigned char pat_spool[MAXPATFILE+2*max_num+MAXPAT]; + unsigned char *patt[max_num]; + unsigned char pat_len[max_num]; + + extern char *strncpy(char *, const char *, size_t); + + void countline(unsigned char *text, int len) + { + int i; + for (i=0; iindex; + p = p->next; + qx = text; + j = 0; + while(tr[patt[pat_index][j]] == tr[*(qx++)]) j++; + if(pat_len[pat_index] <= j) { + if(text >= textend) return; + num_of_matched++; + if(FILENAMEONLY || SILENT) return; + if(COUNT) { + while (*text != '\n') text++; + } + else { + if(FNAME) printf("%s: ",CurrentFileName); + if(!INVERSE) { + while(*(--text) != '\n'); + while(*(++text) != '\n') putchar(*text); + printf("\n"); + MATCHED = 1; + } + else { + while(*(--text) != '\n'); + if(lastout < text) OUT=1; + while(lastout < text) putchar(*lastout++); + if(OUT) { + putchar('\n'); + OUT=0; + } + while(*(++text) != '\n'); + lastout=text+1; + MATCHED = 1; + } + } + } + if(MATCHED) break; + } + MATCHED = 0; + } /* while */ + if(INVERSE && !COUNT) while(lastout <= textend) putchar(*lastout++); + } + + void f_prep(int pat_index, unsigned char *Pattern) + { + int i, m; + register unsigned hash, Mask=15; + m = p_size; + for (i = m-1; i>=(1+LONG); i--) { + hash = (Pattern[i] & Mask); + hash = (hash << 4) + (Pattern[i-1]& Mask); + if(LONG) hash = (hash << 4) + (Pattern[i-2] & Mask); + if(SHIFT1[hash] >= m-1-i) SHIFT1[hash] = m-1-i; + } + if(SHORT) Mask = 255; /* 011111111 */ + hash = 0; + for(i = m-1; i>=0; i--) { + hash = (hash << 4) + (tr[Pattern[i]]&Mask); + } + /* + if(INVERSE) hash = Pattern[1]; + */ + hash=hash&mm; + qt = (struct pat_list *) malloc(sizeof(struct pat_list)); + qt->index = pat_index; + pt = HASH[hash]; + qt->next = pt; + HASH[hash] = qt; + } + + void prepf(int fp) + { + int length=0, i, p=1, num_pat; + unsigned char *pat_ptr=pat_spool; + unsigned Mask = 15; + int num_read; + + while((num_read = read(fp, buf+length, BLOCKSIZE)) > 0) { + length = length + num_read; + if(length > MAXPATFILE) { + fprintf(stderr, "%s: maximum pattern file size is %d\n", Progname, MAXPATFILE); + exit(2); + } + } + buf[length] = '\n'; + i = 0; p=1; + while(imax_num) { + fprintf(stderr, "%s: maximum number of patterns is %d\n", Progname, max_num); + exit(2); + } + for(i=1; i<20; i++) *pat_ptr = i; /* boundary safety zone */ + for(i=0; i< MAXSYM; i++) tr[i] = i; + if(NOUPPER) { + for(i='A'; i<= 'Z'; i++) tr[i] = i + 'a' - 'A'; + } + if(WORDBOUND) { + for(i=0; i<128; i++) if(!isalnum(i)) tr[i] = W_DELIM; + } + for(i=0; i< MAXSYM; i++) tr1[i] = tr[i]&Mask; + num_pat = p-1; + p_size = MAXPAT; + for(i=1 ; i <= num_pat; i++) { + p = strlen(patt[i]); + pat_len[i] = p; + if(p!=0 && p < p_size) p_size = p; + } + if(p_size == 0) { + fprintf(stderr, "the pattern file is empty\n"); + exit(2); + } + if(length > 400 && p_size > 2) LONG = 1; + if(p_size == 1) SHORT = 1; + for(i=0; iindex; + p = p->next; + qx = text-m1; + j = 0; + while(tr[patt[pat_index][j]] == tr[*(qx++)]) j++; + if (j > m1 ) { + if(pat_len[pat_index] <= j) { + if(text > textend) return; + num_of_matched++; + if(FILENAMEONLY || SILENT) return; + MATCHED=1; + if(COUNT) { + while (*text != '\n') text++; + } + else { + if(!INVERSE) { + if(FNAME) printf("%s: ",CurrentFileName); + while(*(--text) != '\n'); + while(*(++text) != '\n') putchar(*text); + printf("\n"); + } + else { + if(FNAME) printf("%s: ",CurrentFileName); + while(*(--text) != '\n'); + if(lastout < text) OUT=1; + while(lastout < text) putchar(*lastout++); + if(OUT) { + putchar('\n'); + OUT=0; + } + while(*(++text) != '\n'); + lastout=text+1; + } + } + /* + else { + if(FNAME) printf("%s: ",CurrentFileName); + while(*(--text) != '\n'); + while(*(++text) != '\n') putchar(*text); + printf("\n"); + } + */ + } + } + if(MATCHED) break; + } + if(!MATCHED) shift = 1; + else { + MATCHED = 0; + shift = m1; + } + } + text = text + shift; + } + if(INVERSE && !COUNT) while(lastout <= textend) putchar(*lastout++); + } + + void mgrep(int fd) + { + register char r_newline = '\n'; + unsigned char text[2*BLOCKSIZE+MAXLINE]; + register int buf_end, num_read, start, end, residue = 0; + + text[MAXLINE-1] = '\n'; /* initial case */ + start = MAXLINE-1; + + while( (num_read = read(fd, text+MAXLINE, BLOCKSIZE)) > 0) + { + if(INVERSE && COUNT) countline(text+MAXLINE, num_read); + buf_end = end = MAXLINE + num_read -1 ; + while(text[end] != r_newline && end > MAXLINE) end--; + residue = buf_end - end + 1 ; + text[start-1] = r_newline; + if(SHORT) m_short(text, start, end); + else monkey1(text, start, end); + if(FILENAMEONLY && num_of_matched) { + printf("%s\n", CurrentFileName); + return; + } + start = MAXLINE - residue; + if(start < 0) { + start = 1; + } + strncpy(text+start, text+end, residue); + } /* end of while(num_read = ... */ + text[MAXLINE] = '\n'; + text[start-1] = '\n'; + if(residue > 1) { + if(SHORT) m_short(text, start, end); + else monkey1(text, start, end); + } + return; + } /* end mgrep */ + + + + + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/parse.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/parse.c:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/parse.c Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,319 ---- + /* the functions in this file parse a string that represents + a regular expression, and return a pointer to a syntax + tree for that regular expression. */ + + #include + #include + #include "re.h" + + #define FALSE 0 + #define TRUE 1 + + #define NextChar(s) *(*s)++ + #define Unexpected(s, c) (**s == NUL || **s == c) + #define Invalid_range(x, y) (x == NUL || x == '-' || x == ']' || x < y) + + extern Stack Push(Stack *s, Re_node v); + extern Re_node Pop(Stack *s); + extern Re_node Top(Stack s); + extern int Size(Stack s); + extern Pset pset_union(Pset s1, Pset s2); + extern Pset create_pos(int n); + + int final_pos, pos_cnt = 0; + + /* retract_token() moves the string pointer back, effectively "unseeing" + the last character seen. It is used only to retract a right paren -- + the idea is that the incarnation of parse_re() that saw the corresponding + left paren is supposed to take care of matching the right paren. This + is necessary to prevent recursive calls from mistakenly eating up someone + else's right parens. */ + + #define retract_token(s) --(*s) + + /* mk_leaf() creates a leaf node that is (usually) a literal node. */ + + Re_node mk_leaf(short opval, short type, char ch, Ch_Set cset) + { + Re_node node; Re_Lit l; + + l = (Re_Lit) new_node(l); + node = (Re_node) new_node(node); + if (l == NULL || node == NULL) return NULL; + lit_type(l) = type; + lit_pos(l) = pos_cnt++; + if (type == C_SET) lit_cset(l) = cset; + else lit_char(l) = ch; /* type == C_LIT */ + Op(node) = opval; + Lit(node) = l; + Nullable(node) = FALSE; + Firstpos(node) = create_pos(lit_pos(l)); + Lastpos(node) = Firstpos(node); + return node; + } + + /* parse_cset() takes a pointer to a pointer to a string and parses + a prefix of it denoting a character set literal. It returns a pointer + to a Re_node node, NULL if there is an error. */ + + Re_node parse_cset(char **s) + { + Ch_Set cs_ptr, curr_ptr, prev_ptr; + char ch; + Ch_Range range; + + if (Unexpected(s, ']')) return NULL; + curr_ptr = (Ch_Set) new_node(curr_ptr); cs_ptr = curr_ptr; + while (!Unexpected(s, ']')) { + range = (Ch_Range)new_node(range); + curr_ptr->elt = range; + ch = NextChar(s); + if (ch == '-') return NULL; /* invalid range */ + range->low_bd = ch; + if (**s == NUL) return NULL; + else if (**s == '-') { /* character range */ + (*s)++; + if (Invalid_range(**s, ch)) return NULL; + else range->hi_bd = NextChar(s); + } + else range->hi_bd = ch; + prev_ptr = curr_ptr; + curr_ptr = (Ch_Set) new_node(curr_ptr); + prev_ptr->rest = curr_ptr; + }; + if (**s == ']') { + prev_ptr->rest = NULL; + return mk_leaf(LITERAL, C_SET, NUL, cs_ptr); + } + else return NULL; + } /* parse_cset */ + + + /* parse_wildcard() "parses" a wildcard -- a wildcard is treated as a + character range whose values span all ASCII values. parse_wildcard() + creates a node representing such a range. */ + + Re_node parse_wildcard(void) + { + Ch_Set s; Ch_Range r; + + r = (Ch_Range) new_node(r); + r->low_bd = ASCII_MIN; /* smallest ASCII value */ + r->hi_bd = ASCII_MAX; /* greatest ASCII value */ + s = (Ch_Set) new_node(s); + s->elt = r; + s->rest = NULL; + return mk_leaf(LITERAL, C_SET, NUL, s); + } + + /* parse_chlit() parses a character literal. It is assumed that the + character in question does not have any special meaning. It returns + a pointer to a node for that literal. */ + + Re_node parse_chlit(char ch) + { + if (ch == NUL) return NULL; + else return mk_leaf(LITERAL, C_LIT, ch, NULL); + } + + + /* get_token() returns the next token -- this may be a character + literal, a character set, an escaped character, a punctuation (i.e. + parenthesis), or an operator. It traverses the character string + representing the RE, given by a pointer s; leaves s positioned + immediately after the unit it parsed, and returns a pointer to + a token node for that unit. */ + + Tok_node get_token(char **s) + { + Tok_node rn = NULL; + + if (s == NULL || *s == NULL) return NULL; /* error */ + rn = (Tok_node) new_node(rn); + if (**s == NUL) tok_type(rn) = EOS; /* end of string */ + else { + switch (**s) { + case '.': /* wildcard */ + tok_type(rn) = LITERAL; + tok_val(rn) = parse_wildcard(); + if (tok_val(rn) == NULL) return NULL; + break; + case '[': /* character set literal */ + (*s)++; + tok_type(rn) = LITERAL; + tok_val(rn) = parse_cset(s); + if (tok_val(rn) == NULL) return NULL; + break; + case '(': + tok_type(rn) = LPAREN; + break; + case ')' : + tok_type(rn) = RPAREN; + break; + case '*' : + tok_type(rn) = OPSTAR; + break; + case '|' : + tok_type(rn) = OPALT; + break; + case '?' : + tok_type(rn) = OPOPT; + break; + case '\\': /* escaped character */ + (*s)++; + default : /* must be ordinary character */ + tok_type(rn) = LITERAL; + tok_val(rn) = parse_chlit(**s); + if (tok_val(rn) == NULL) return NULL; + break; + } /* switch (**s) */ + (*s)++; + } /* else */ + return rn; + } + + /* cat2() takes a stack of RE-nodes and, if the stack contains + more than one node, returns the stack obtained by condensing + the top two nodes of the stack into a single CAT-node. If there + is only one node on the stack, nothing is done. */ + + Stack cat2(Stack *stk) + { + Re_node r; + + if (stk == NULL) return NULL; + if (*stk == NULL || (*stk)->next == NULL) return *stk; + r = (Re_node) new_node(r); + if (r == NULL) return NULL; /* can't allocate memory */ + Op(r) = OPCAT; + Rchild(r) = Pop(stk); + Lchild(r) = Pop(stk); + if (Push(stk, r) == NULL) return NULL; + Nullable(r) = Nullable(Lchild(r)) && Nullable(Rchild(r)); + if (Nullable(Lchild(r))) + Firstpos(r) = pset_union(Firstpos(Lchild(r)), Firstpos(Rchild(r))); + else Firstpos(r) = Firstpos(Lchild(r)); + if (Nullable(Rchild(r))) + Lastpos(r) = pset_union(Lastpos(Lchild(r)), Lastpos(Rchild(r))); + else Lastpos(r) = Lastpos(Rchild(r)); + return *stk; + } + + /* wrap() takes a stack and an operator, takes the top element of the + stack and "wraps" that operator around it, then puts this back on the + stack and returns the resulting stack. */ + + Stack wrap(Stack *s, short opv) + { + Re_node r; + + if (s == NULL || *s == NULL) return NULL; + r = (Re_node) new_node(r); + if (r == NULL) return NULL; + Op(r) = opv; + Child(r) = Pop(s); + if (Push(s, r) == NULL) return NULL; + Nullable(r) = TRUE; + Firstpos(r) = Firstpos(Child(r)); + Lastpos(r) = Lastpos(Child(r)); + return *s; + } + + /* mk_alt() takes a stack and a regular expression, creates an ALT-node + from the top of the stack and the given RE, and replaces the top-of-stack + by the resulting ALT-node. */ + + Stack mk_alt(Stack *s, Re_node r) + { + Re_node node; + + if (s == NULL || *s == NULL || r == NULL) return NULL; + node = (Re_node) new_node(node); + if (node == NULL) return NULL; + Op(node) = OPALT; + Lchild(node) = Pop(s); + Rchild(node) = r; + if (Push(s, node) == NULL) return NULL; + Nullable(node) = Nullable(Lchild(node)) || Nullable(Rchild(node)); + Firstpos(node) = pset_union(Firstpos(Lchild(node)), Firstpos(Rchild(node))); + Lastpos(node) = pset_union(Lastpos(Lchild(node)), Lastpos(Rchild(node))); + return *s; + } + + /* parse_re() takes a pointer to a string and traverses that string, + returning a pointer to a syntax tree for the regular expression + represented by that string, NULL if there is an error. */ + + Re_node parse_re(char **s, short end) + { + Stack stk = NULL, temp; + Tok_node next_token; + Re_node re = NULL; + + if (s == NULL || *s == NULL) return NULL; + while (TRUE) { + next_token = get_token(s); + if (next_token == NULL) return NULL; + switch (tok_type(next_token)) { + case RPAREN: + retract_token(s); + case EOS: + if (end == tok_type(next_token)) return Top(cat2(&stk)); + else return NULL; + case LPAREN: + re = parse_re(s, RPAREN); + if (Push(&stk, re) == NULL) return NULL; + if (tok_type(get_token(s)) != RPAREN || re == NULL) return NULL; + if (Size(stk) > 2) { + temp = stk->next; + stk->next = cat2(&temp); /* condense CAT nodes */ + if (stk->next == NULL) return NULL; + else stk->size = stk->next->size + 1; + } + break; + case OPSTAR: + if (wrap(&stk, OPSTAR) == NULL) return NULL; + break; + case OPOPT: + if (wrap(&stk, OPOPT) == NULL) return NULL; + break; + case OPALT: + if (cat2(&stk) == NULL) return NULL; + re = parse_re(s, end); + if (re == NULL) return NULL; + if (mk_alt(&stk, re) == NULL) return NULL; + break; + case LITERAL: + if (Push(&stk, tok_val(next_token)) == NULL) return NULL; + if (Size(stk) > 2) { + temp = stk->next; + stk->next = cat2(&temp); /* condense CAT nodes */ + if (stk->next == NULL) return NULL; + else stk->size = stk->next->size + 1; + } + break; + default: + printf("parse_re: unknown token type %d\n", tok_type(next_token)); + break; + } + } + } + + /* parse() essentially just calls parse_re(). Its purpose is to stick an + end-of-string token at the end of the syntax tree returned by parse_re(). + It should really be done in parse_re, but the recursion there makes it + more desirable to have it here. */ + + Re_node parse(char *s) + { + Re_node tree, temp; + Stack stk = NULL; + + tree = parse_re(&s, NUL); + if (tree == NULL || Push(&stk, tree) == NULL) return NULL; + temp = mk_leaf(EOS, C_LIT, NUL, NULL); + if (temp == NULL || Push(&stk, temp) == NULL) return NULL; + final_pos = --pos_cnt; + return Top(cat2(&stk)); + } + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/preprocess.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/preprocess.c:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/preprocess.c Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,216 ---- + /* Copyright (c) 1991 Sun Wu and Udi Manber. All Rights Reserved. */ + /* substitute metachar with special symbol */ + /* if regularr expression, then set flag REGEX */ + /* if REGEX and MULTIPAT then report error message, */ + /* -w only for single word pattern. If WORDBOUND & MULTIWORD error */ + /* process start of line, endof line symbol, */ + /* process -w WORDBOUND option, append special symbol at begin&end of */ + /* process -d option before this routine */ + /* the delimiter pattern is in D_pattern (need to end with '; ') */ + /* if '-t' (suggestion: how about -B) the pattern is passed to sgrep */ + /* and doesn't go here */ + /* in that case, -d is ignored? or not necessary */ + /* upon return, Pattern contains the pattern to be processed by maskgen */ + /* D_pattern contains transformed D_pattern */ + #include + #include + #include "agrep.h" + + extern int SIMPLEPATTERN, WHOLELINE, REGEX, RE_ERR, DELIMITER, TAIL, WORDBOUND; + extern int HEAD; + extern CHAR Progname[]; + extern int D_length; + extern int table[WORD][WORD]; + + extern int init(char *s, int table[32][32]); + + void preprocess(CHAR *D_pattern, CHAR *Pattern) /* need two parameters */ + { + CHAR temp[Maxline], *r_pat, *old_pat; /* r_pat for r.e. */ + CHAR old_D_pat[MaxDelimit]; + int i, j=0, rp=0, m, t=0, num_pos, ANDON = 0; + int d_end ; + int IN_RANGE=0; + old_pat = Pattern; /* to remember the starting position */ + m = strlen(Pattern); + for(i=0; i< m; i++) { + if(Pattern[i] == '\\') i++; + else if(Pattern[i] == '|' || Pattern[i] == '*' ) REGEX = ON; + } + r_pat = (CHAR *) malloc(strlen(Pattern)+2*strlen(D_pattern)); + strcpy(temp, D_pattern); + d_end = t = strlen(temp); /* size of D_pattern, including '; ' */ + if (WHOLELINE) { temp[t++] = LANGLE; + temp[t++] = NNLINE; + temp[t++] = RANGLE; + temp[t] = '\0'; + strcat(temp, Pattern); + m = strlen(temp); + temp[m++] = LANGLE; + temp[m++] = '\n'; + temp[m++] = RANGLE; + temp[m] = '\0'; } + else { + if (WORDBOUND) { temp[t++] = LANGLE; + temp[t++] = WORDB; + temp[t++] = RANGLE; + temp[t] = '\0'; } + strcat(temp, Pattern); + m = strlen(temp); + if (WORDBOUND) { temp[m++] = LANGLE; + temp[m++] = WORDB; + temp[m++] = RANGLE; } + temp[m] = '\0'; + } + /* now temp contains augmented pattern , m it's size */ + + D_length = 0; + for (i=0, j=0; i< d_end-2; i++) { + switch(temp[i]) + { + case '\\' : i++; + Pattern[j++] = temp[i]; + old_D_pat[D_length++] = temp[i]; + break; + case '<' : Pattern[j++] = LANGLE; + break; + case '>' : Pattern[j++] = RANGLE; + break; + case '^' : Pattern[j++] = '\n'; + old_D_pat[D_length++] = temp[i]; + break; + case '$' : Pattern[j++] = '\n'; + old_D_pat[D_length++] = temp[i]; + break; + default : Pattern[j++] = temp[i]; + old_D_pat[D_length++] = temp[i]; + break; + } + } + if(D_length > MAXDELIM) { + fprintf(stderr, "%s: delimiter pattern too long\n", Progname); + exit(2); + } + Pattern[j++] = ANDPAT; + old_D_pat[D_length] = '\0'; + strcpy(D_pattern, old_D_pat); + D_length++; + /* + Pattern[j++] = ' '; + */ + Pattern[j] = '\0'; + rp = 0; + if(REGEX) { + r_pat[rp++] = '.'; /* if REGEX: always append '.' in front */ + r_pat[rp++] = '('; + Pattern[j++] = NOCARE; + HEAD = ON; + } + for (i=d_end; i < m ; i++) + { + switch(temp[i]) + { + case '\\': i++; Pattern[j++] = temp[i]; + r_pat[rp++] = 'o'; /* the symbol doesn't matter */ + break; + case '#': if(REGEX) { + Pattern[j++] = NOCARE; + r_pat[rp++] = '.'; + r_pat[rp++] = '*'; + break; } + Pattern[j++] = WILDCD; + break; + case '(': Pattern[j++] = LPARENT; + r_pat[rp++] = '('; + break; + case ')': Pattern[j++] = RPARENT; + r_pat[rp++] = ')'; + break; + case '[': Pattern[j++] = LRANGE; + r_pat[rp++] = '['; + IN_RANGE = ON; + break; + case ']': Pattern[j++] = RRANGE; + r_pat[rp++] = ']'; + IN_RANGE = OFF; + break; + case '<': Pattern[j++] = LANGLE; + break; + case '>': Pattern[j++] = RANGLE; + break; + case '^': if (temp[i-1] == '[') Pattern[j++] = NOTSYM; + else Pattern[j++] = '\n'; + r_pat[rp++] = '^'; + break; + case '$': Pattern[j++] = '\n'; + r_pat[rp++] = '$'; + break; + case '.': Pattern[j++] = NOCARE; + r_pat[rp++] = '.'; + break; + case '*': Pattern[j++] = STAR; + r_pat[rp++] = '*'; + break; + case '|': Pattern[j++] = ORSYM; + r_pat[rp++] = '|'; + break; + case ',': Pattern[j++] = ORPAT; + RE_ERR = ON; + break; + case ';': if(ANDON) RE_ERR = ON; + Pattern[j++] = ANDPAT; + ANDON = ON; + break; + case '-': if(IN_RANGE) { + Pattern[j++] = HYPHEN; + r_pat[rp++] = '-'; + } + else { + Pattern[j++] = temp[i]; + r_pat[rp++] = temp[i]; + } + break; + case NNLINE : + Pattern[j++] = temp[i]; + r_pat[rp++] = 'N'; + break; + default: Pattern[j++] = temp[i]; + r_pat[rp++] = temp[i]; + break; + } + } + if(REGEX) { /* append ').' at end of regular expression */ + r_pat[rp++] = ')'; + r_pat[rp++] = '.'; + Pattern[j++] = NOCARE; + TAIL = ON; + } + Pattern[j] = '\0'; + m = j; + r_pat[rp] = '\0'; + if(REGEX) + { + if(DELIMITER || WORDBOUND) { + fprintf(stderr, "%s: -d or -w option is not supported for this pattern\n", Progname); + exit(2); + } + if(RE_ERR) { + fprintf(stderr, "%s: illegal regular expression\n", Progname); + exit(2); + } + while(*Pattern != NOCARE && m-- > 0) Pattern++; /* poit to . */ + num_pos = init(r_pat, table); + if(num_pos <= 0) { + fprintf(stderr, "%s: illegal regular expression\n", Progname); + exit(2); + } + if(num_pos > 30) { + fprintf(stderr, "%s: regular expression too long\n", Progname); + exit(2); + } + strcpy(old_pat, Pattern); /* do real change to the Pattern to be returned */ + return; + } /* if regex */ + + return; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/re.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/re.h:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/re.h Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,129 ---- + /************************************************************* + * * + * Macros defining special characters. * + * * + *************************************************************/ + + #define NUL '\0' + #define ASCII_MIN '\001' + #define ASCII_MAX '\177' + + /************************************************************* + * * + * Macros defining lexical categories. * + * * + *************************************************************/ + + #define C_LIT 0 /* individual character literal */ + #define C_SET 1 /* character set literal */ + + #define EOS 0 /* end-of-string */ + #define LITERAL 1 + #define OPSTAR 2 + #define OPALT 3 + #define OPOPT 4 + #define OPCAT 5 + #define LPAREN 6 + #define RPAREN 7 + + /************************************************************* + * * + * Macros for manipulating syntax tree nodes. * + * * + *************************************************************/ + + #define lit_type(x) (x->l_type) + #define lit_pos(x) (x->pos) + #define lit_char(x) ((x->val).c) + #define lit_cset(x) ((x->val).cset) + + #define tok_type(x) (x->type) + #define tok_val(x) (x->val) + #define tok_op(x) (x->val->op) + #define tok_lit(x) ((x->val->refs).lit) + + #define Op(x) (x->op) + #define Lit(x) ((x->refs).lit) + #define Child(x) ((x->refs).child) + #define Lchild(x) ((x->refs).children.l_child) + #define Rchild(x) ((x->refs).children.r_child) + #define Nullable(x) (x->nullable) + #define Firstpos(x) (x->firstposn) + #define Lastpos(x) (x->lastposn) + + /************************************************************* + * * + * Macros for manipulating DFA states and sets of states. * + * * + *************************************************************/ + + #define Positions(x) (x->posns) + #define Final_St(x) (x->final) + #define Goto(x, c) ((x->trans)[c]) + #define Next_State(x) ((x)->next_state) + + /*************************************************************/ + + #define new_node(x) malloc(sizeof(*x)) + + typedef struct { /* character range literals */ + char low_bd, hi_bd; + } *Ch_Range; + + typedef struct ch_set { /* character set literals */ + Ch_Range elt; /* rep. as list of ranges */ + struct ch_set *rest; + } *Ch_Set; + + typedef struct { /* regular expression literal */ + int pos; /* position in syntax tree */ + short l_type; /* type of literal */ + union { + char c; /* for character literals */ + Ch_Set cset; /* for character sets */ + } val; + } *Re_Lit, *(*Re_lit_array)[]; + + typedef struct pnode { + int posnum; + struct pnode *nextpos; + } *Pset, *(*Pset_array)[]; + + typedef struct rnode { /* regular expression node */ + short op; /* operator at that node */ + union { + Re_Lit lit; /* child is a leaf node */ + struct rnode *child; /* child of unary op */ + struct { + struct rnode *l_child; + struct rnode *r_child; + } children; /* children of binary op */ + } refs; + short nullable; + Pset firstposn, lastposn; + } *Re_node; + + typedef struct { /* token node */ + short type; + Re_node val; + } *Tok_node; + + + typedef struct snode { + Re_node val; + int size; + struct snode *next; + } *Stack; + + typedef struct dfa_st { + Pset posns; + int final; /* 1 if the state is a final state, 0 o/w */ + struct dfa_st *trans[128]; + } *Dfa_state; + + typedef struct dfa_stset { + Dfa_state st; + struct dfa_stset *next_state; + } *Dfa_state_set; + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/sgrep.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/sgrep.c:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/sgrep.c Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,665 ---- + /* Copyright (c) 1991 Sun Wu and Udi Manber. All Rights Reserved. */ + #include + #include + #include + #include + #define MAXSYM 256 + #define MAXMEMBER 8192 + #define CHARTYPE unsigned char + #define MaxError 20 + #define MAXPATT 256 + #define MAXLINE 1024 + #define MaxCan 2048 + #define BLOCKSIZE 8192 + #define MAX_SHIFT_2 4096 + #define ON 1 + #define LOG_ASCII 8 + #define LOG_DNA 3 + #define MAXMEMBER_1 65536 + #define LONG_EXAC 20 + #define LONG_APPX 24 + #define W_DELIM 128 + + extern COUNT, FNAME, SILENT, FILENAMEONLY, num_of_matched; + extern DNA ; /* DNA flag is set in checksg when pattern is DNA pattern and + p_size > 16 */ + extern WORDBOUND, WHOLELINE, NOUPPER; + extern unsigned char CurrentFileName[], Progname[]; + extern unsigned Mask[]; + extern unsigned endposition; + + unsigned char BSize; /* log_c m */ + unsigned char char_map[MAXSYM]; + + + /* data area */ + int shift_1; + CHARTYPE SHIFT[MAXSYM]; + CHARTYPE MEMBER[MAXMEMBER]; + CHARTYPE pat[MAXPATT]; + unsigned Hashmask; + char MEMBER_1[MAXMEMBER_1]; + CHARTYPE TR[MAXSYM]; + + void char_tr(unsigned char *pat, int *m) + { + int i; + unsigned char temp[MAXPATT]; + for(i=0; i D) last = last - 1; + if(last >= m) return(text - textbegin - 1); + if(*text == '\n') { + last = D; + for(c = 0; c<=m1; c++) A[c] = B[c] = c; + } + for (k = 1; k <= last; k++) + { + cost = A[k-1]+1; + if (pat[k-1] != *text) + { if (A[k]+1 < cost) cost = A[k]+1; + if (B[k-1]+1 < cost) cost = B[k-1]+1; } + else cost = cost -1; + B[k] = cost; + } + if(pat[last] == *text++) { B[last+1] = A[last]; last++; } + if(B[last] < D) B[last+1] = B[last++]+1; + while (B[last] > D) last = last -1; + if(last >= m) return(text - textbegin - 1); + if(*text == '\n') { + last = D; + for(c = 0; c<=m1; c++) A[c] = B[c] = c; + } + } + return(0); + } + + /* SUN: bm assumes that the content of text[n]...text[n+m-1] is + pat[m-1] such that the skip loop is guaranteed to terminated */ + + void bm(CHARTYPE *pat, int m, CHARTYPE *text, CHARTYPE *textend) + { + register int shift; + register int m1, j, d1; + + /* + printf("%d\t", textend - text); + printf("%c, %c", *text, *textend); + */ + + d1 = shift_1; /* at least 1 */ + m1 = m - 1; + shift = 0; + while (text <= textend) { + shift = SHIFT[*(text += shift)]; + while(shift) { + shift = SHIFT[*(text += shift)]; + shift = SHIFT[*(text += shift)]; + shift = SHIFT[*(text += shift)]; + } + j = 0; + while(TR[pat[m1 - j]] == TR[*(text - j)]) { + if(++j == m) break; /* if statement can be + saved, but for safty ... */ + } + if (j == m ) { + if(text > textend) return; + if(WORDBOUND) { + if(TR[*(text+1)] != W_DELIM) goto CONT; + if(TR[*(text-m)] != W_DELIM) goto CONT; + } + num_of_matched++; + if(FILENAMEONLY) return; + if(!(COUNT)) { + if(FNAME) printf("%s: ", CurrentFileName); + while(*(--text) != '\n'); + while(*(++text) != '\n') putchar(*(text)); + putchar(*text); + } + else { while(*text != '\n') text++; } + CONT: + shift = 1; + } + else shift = d1; + } + return; + } + + + /* initmask() initializes the mask table for the pattern */ + /* endposition is a mask for the endposition of the pattern */ + /* endposition will contain k mask bits if the pattern contains k fragments */ + void initmask(CHARTYPE *pattern, unsigned *Mask, register int m, register int D, unsigned *endposition) + { + register unsigned Bit1, c; + register int i, j, frag_num; + + Bit1 = 1 << 31; /* the first bit of Bit1 is 1, others 0. */ + frag_num = D+1; *endposition = 0; + for (i = 0; i < frag_num; i++) *endposition = *endposition | (Bit1 >> i); + *endposition = *endposition >> (m - frag_num); + for(i = 0; i < m; i++) + if (pattern[i] == '^' || pattern[i] == '$') { + pattern[i] = '\n'; + } + for(i = 0; i < MAXSYM; i++) Mask[i] = ~0; + for(i = 0; i < m; i++) /* initialize the mask table */ + { c = pattern[i]; + for ( j = 0; j < m; j++) + if( c == pattern[j] ) + Mask[c] = Mask[c] & ~( Bit1 >> j ) ; + } + } + + void prep(CHARTYPE *Pattern, register int M, register int D) /* preprocessing for partitioning_bm */ + { + register int i, j, k, p, shift; + register unsigned m; + unsigned hash, b_size = 3; + m = M/(D+1); + p = M - m*(D+1); + for (i = 0; i < MAXSYM; i++) SHIFT[i] = m; + for (i = M-1; i>=p ; i--) { + shift = (M-1-i)%m; + hash = Pattern[i]; + if(SHIFT[hash] > shift) SHIFT[hash] = shift; + } + #ifdef DEBUG + for(i=0; i Candidate[cdx][1]) { + Candidate[++cdx][0] = i-M-D-2; + Candidate[cdx][1] = i+M+D; } + else Candidate[cdx][1] = i+M+D; + shift = d1; + } + else shift = d1; + } + + + text = textstart; + n = textend - textstart; + r_newline = '\n'; + /* for those candidate areas, find the D-error matches */ + if(Candidate[1][0] < 0) Candidate[1][0] = 0; + endpos = endposition; /* the mask table and the endposition */ + Bit1 = (1 << 31); + for(round = 0; round <= cdx; round++) + { i = Candidate[round][0] ; + if(Candidate[round][1] > n) Candidate[round][1] = n; + if(i < 0) i = 0; + #ifdef DEBUG + printf("round: %d, start=%d, end=%d, ", round, i, Candidate[round][1]); + #endif + R1[0] = R2[0] = ~0; + R1[1] = R2[1] = ~Bit1; + for(k = 1; k <= D; k++) R1[k] = R2[k] = (R1[k-1] >> 1) & R1[k-1]; + while (i < Candidate[round][1]) + { + c = text[i++]; + if(c == r_newline) { + for(k = 0 ; k <= D; k++) R1[k] = R2[k] = (~0 ); + } + r1 = Mask[c]; + R1[0] = (R2[0] >> 1) | r1; + for(k=1; k<=D; k++) + R1[k] = ((R2[k] >> 1) | r1) & R2[k-1] & ((R1[k-1] & R2[k-1]) >> 1); + if((R1[D] & endpos) == 0) { + num_of_matched++; + if(FILENAMEONLY) { return; } + currentpos = i; + if(i <= lastend) i = lastend; + else { + s_output(text, ¤tpos); + i = currentpos; + } + lastend = i; + for(k=0; k<=D; k++) R1[k] = R2[k] = ~0; + } + c = text[i++]; + if(c == r_newline) { + for(k = 0 ; k <= D; k++) R1[k] = R2[k] = (~0 ); + } + r1 = Mask[c]; + R2[0] = (R1[0] >> 1) | r1; + for(k = 1; k <= D; k++) + R2[k] = ((R1[k] >> 1) | r1) & R1[k-1] & ((R1[k-1] & R2[k-1]) >> 1); + if((R2[D] & endpos) == 0) { currentpos = i; + num_of_matched++; + if(FILENAMEONLY) { return; } + if(i <= lastend) i = lastend; + else { + s_output(text, ¤tpos); + i = currentpos; + } + lastend = i; + for(k=0; k<=D; k++) R1[k] = R2[k] = ~0; + } + } + } + return; + } + + void prep_bm(unsigned char *Pattern, register m) + { + int i; + unsigned hash; + unsigned char lastc; + for (i = 0; i < MAXSYM; i++) SHIFT[i] = m; + for (i = m-1; i>=0; i--) { + hash = TR[Pattern[i]]; + if(SHIFT[hash] >= m - 1) SHIFT[hash] = m-1-i; + } + shift_1 = m-1; + lastc = TR[Pattern[m-1]]; + for (i= m-2; i>=0; i--) { + if(TR[Pattern[i]] == lastc ) + { shift_1 = m-1 - i; i = -1; } + } + if(shift_1 == 0) shift_1 = 1; + if(NOUPPER) for(i='A'; i<='Z'; i++) SHIFT[i] = SHIFT[i + 'a' - 'A']; + #ifdef DEBUG + for(i='a'; i<='z'; i++) printf("%c: %d", i, SHIFT[i]); printf("\n"); + for(i='A'; i<='Z'; i++) printf("%c: %d", i, SHIFT[i]); printf("\n"); + #endif + } + + + /* a_monkey() the approximate monkey move */ + + void a_monkey( register CHARTYPE *pat, register int m, register CHARTYPE *text, register CHARTYPE *textend, + register int D ) + { + register CHARTYPE *oldtext; + register unsigned hash, hashmask, suffix_error; + register int m1 = m-1-D, pos; + + hashmask = Hashmask; + oldtext = text; + while (text < textend) { + text = text+m1; + suffix_error = 0; + while(suffix_error <= D) { + hash = *text--; + while(MEMBER_1[hash]) { + hash = ((hash << LOG_ASCII) + *(text--)) & hashmask; + } + suffix_error++; + } + if(text <= oldtext) { + if((pos = verify(m, 2*m+D, D, pat, oldtext)) > 0) { + text = oldtext+pos; + if(text > textend) return; + num_of_matched++; + if(FILENAMEONLY) return; + if(!(COUNT)) { + if(FNAME) printf("%s: ", CurrentFileName); + while(*(--text) != '\n'); + while(*(++text) != '\n') putchar(*text); + printf("\n"); + } + else { + while(*text != '\n') text++; + } + } + else { + text = oldtext + m; + } + } + oldtext = text; + } + } + + /* monkey uses two characters for delta_1 shifting */ + + CHARTYPE SHIFT_2[MAX_SHIFT_2]; + + void monkey( register CHARTYPE *pat, register int m, register CHARTYPE *text, register CHARTYPE *textend ) + { + register unsigned hash; + register CHARTYPE shift; + register int m1, j; + register unsigned r_newline; + + r_newline = '\n'; + + m1 = m - 1; + text = text+m1; + while (text < textend) { + hash = *text; + hash = (hash << 3) + *(text-1); + shift = SHIFT_2[hash]; + while(shift) { + text = text + shift; + hash = (*text << 3) + *(text-1); + shift = SHIFT_2[hash]; + } + j = 0; + while(TR[pat[m1 - j]] == TR[*(text - j)]) { if(++j == m) break; } + if (j == m ) { + if(text >= textend) return; + num_of_matched++; + if(FILENAMEONLY) return; + if(COUNT) { + while (*text != r_newline) text++; + text--; + } + else { + if(FNAME) printf("%s: ", CurrentFileName); + while(*(--text) != r_newline); + while(*(++text) != r_newline) putchar(*text); + printf("\n"); + text--; + } + } + text++; + } + } + + void am_preprocess(CHARTYPE *Pattern) + { + int i, m; + m = strlen(Pattern); + for (i = 1, Hashmask = 1 ; i<16 ; i++) Hashmask = (Hashmask << 1) + 1 ; + for (i = 0; i < MAXMEMBER_1; i++) MEMBER_1[i] = 0; + for (i = m-1; i>=0; i--) { + MEMBER_1[Pattern[i]] = 1; + } + for (i = m-1; i > 0; i--) { + MEMBER_1[(Pattern[i] << LOG_ASCII) + Pattern[i-1]] = 1; + } + } + + /* preprocessing for monkey() */ + + void m_preprocess(CHARTYPE *Pattern) + { + int i, j, m; + unsigned hash; + m = strlen(Pattern); + for (i = 0; i < MAX_SHIFT_2; i++) SHIFT_2[i] = m; + for (i = m-1; i>=1; i--) { + hash = Pattern[i]; + hash = hash << 3; + for (j = 0; j< MAXSYM; j++) { + if(SHIFT_2[hash+j] == m) SHIFT_2[hash+j] = m-1; + } + hash = hash + Pattern[i-1]; + if(SHIFT_2[hash] >= m - 1) SHIFT_2[hash] = m-1-i; + } + shift_1 = m-1; + for (i= m-2; i>=0; i--) { + if(Pattern[i] == Pattern[m-1] ) + { shift_1 = m-1 - i; i = -1; } + } + if(shift_1 == 0) shift_1 = 1; + SHIFT_2[0] = 0; + } + + /* monkey4() the approximate monkey move */ + + char *MEMBER_D; + + void monkey4( register unsigned char *pat, register int m, register unsigned char *text, register unsigned char *textend, + register int D ) + { + register unsigned char *oldtext; + register unsigned hash, hashmask, suffix_error; + register int m1=m-1-D, pos; + + hashmask = Hashmask; + oldtext = text ; + while (text < textend) { + text = text + m1; + suffix_error = 0; + while(suffix_error <= D) { + hash = char_map[*text--]; + hash = ((hash << LOG_DNA) + char_map[*(text--)]) & hashmask; + while(MEMBER_D[hash]) { + hash = ((hash << LOG_DNA) + char_map[*(text--)]) & hashmask; + } + suffix_error++; + } + if(text <= oldtext) { + if((pos = verify(m, 2*m+D, D, pat, oldtext)) > 0) { + text = oldtext+pos; + if(text > textend) return; + num_of_matched++; + if(FILENAMEONLY) return; + if(!(COUNT)) { + if(FNAME) printf("%s:", CurrentFileName); + while(*(--text) != '\n'); + while(*(++text) != '\n') putchar(*text); + printf("\n"); + text++; + } + else { + while(*text != '\n') text++; + text++; + } + } + else text = oldtext + m; + } + oldtext = text; + } + } + + int blog(int base, int m ) + { + int i, exp; + exp = base; + m = m + m/2; + for (i = 1; exp < m; i++) exp = exp * base; + return(i); + } + + void prep4(char *Pattern, int m) + { + int i, j, k; + unsigned hash; + + for(i=0; i< MAXSYM; i++) char_map[i] = 0; + char_map['a'] = char_map['A'] = 4; + char_map['g'] = char_map['g'] = 1; + char_map['t'] = char_map['t'] = 2; + char_map['c'] = char_map['c'] = 3; + char_map['n'] = char_map['n'] = 5; + + BSize = blog(4, m); + for (i = 1, Hashmask = 1 ; i= j; i--) { + hash = 0; + for(k=0; k <= j; k++) + hash = (hash << LOG_DNA) +char_map[Pattern[i-k]]; + #ifdef DEBUG + printf("< %d >, ", hash); + #endif + MEMBER_D[hash] = 1; + } + } + } + + void sgrep(CHARTYPE *pat, int m, int fd, int D) + { + CHARTYPE text[BLOCKSIZE+2*MAXLINE+MAXPATT]; /* input text stream */ + int offset = 2*MAXLINE; + int buf_end, num_read, i, start, end, residue = 0; + if(pat[0] == '^' || pat[0] == '$') pat[0] = '\n'; + if(pat[m-1] == '^' || pat[m-1] == '$') pat[m-1] = '\n'; + char_tr(pat, &m); /* will change pat, and m if WHOLELINE is ON */ + text[offset-1] = '\n'; /* initial case */ + for(i=0; i < MAXLINE; i++) text[i] = 0; /* security zone */ + start = offset; + if(WHOLELINE) start--; + if(m >= MAXPATT) { + fprintf(stderr, "%s: pattern too long\n", Progname); + exit(2); + } + if(D == 0) { + if(m > LONG_EXAC) m_preprocess(pat); + else prep_bm(pat, m); + } + else if (DNA) prep4(pat, m); + else if(m >= LONG_APPX) am_preprocess(pat); + else { + prep(pat, m, D); + initmask(pat, Mask, m, 0, &endposition); + } + for(i=1; i<=m; i++) text[BLOCKSIZE+offset+i] = pat[m-1]; + /* to make sure the skip loop in bm() won't go out of bound */ + while( (num_read = read(fd, text+offset, BLOCKSIZE)) > 0) + { + buf_end = end = offset + num_read -1 ; + while(text[end] != '\n' && end > offset) end--; + residue = buf_end - end + 1 ; + text[start-1] = '\n'; + if(D==0) { + if(m > LONG_EXAC) monkey(pat, m, text+start, text+end); + else bm(pat, m, text+start, text+end); + } + else { + if(DNA) monkey4( pat, m, text+start, text+end, D ); + else { + if(m >= LONG_APPX) a_monkey(pat, m, text+start, text+end, D); + else agrep(pat, m, text+start, text+end, D); + } + } + if(FILENAMEONLY && num_of_matched) { + printf("%s\n", CurrentFileName); + return; } + start = offset - residue ; + if(start < MAXLINE) { + start = MAXLINE; + } + strncpy(text+start, text+end, residue); + start++; + } /* end of while(num_read = ... */ + return; + } /* end sgrep */ + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/utilities.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/utilities.c:1.1 *** /dev/null Tue Oct 5 13:03:12 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/agrep/utilities.c Tue Oct 5 13:02:58 2004 *************** *** 0 **** --- 1,127 ---- + /* this file contains various utility functions for accessing + and manipulating regular expression syntax trees. */ + + #include + #include + #include "re.h" + + /************************************************************************/ + /* */ + /* the following routines implement an abstract data type "stack". */ + /* */ + /************************************************************************/ + + Stack Push(Stack *s, Re_node v) + { + Stack node; + + node = (Stack) new_node(node); + if (s == NULL || node == NULL) return NULL; /* can't allocate */ + node->next = *s; + node->val = v; + if (*s == NULL) node->size = 1; + else node->size = (*s)->size + 1; + *s = node; + return *s; + } + + Re_node Pop(Stack *s) + { + Re_node node; + Stack temp; + + if (s == NULL || *s == NULL) return NULL; + else { + temp = *s; + node = (*s)->val; + *s = (*s)->next; + free(temp); + return node; + } + } + + Re_node Top(Stack s) + { + if (s == NULL) return NULL; + else return s->val; + } + + int Size(Stack s) + { + if (s == NULL) return 0; + else return s->size; + } + + /************************************************************************/ + /* */ + /* the following routines manipulate sets of positions. */ + /* */ + /************************************************************************/ + + int occurs_in(int n, Pset p) + { + while (p != NULL) + if (n == p->posnum) return 1; + else p = p->nextpos; + return 0; + } + + /* pset_union() takes two position-sets and returns their union. */ + + Pset pset_union(Pset s1, Pset s2) + { + Pset hd, curr, new1; + + hd = NULL; curr = NULL; + while (s1 != NULL) { + if (!occurs_in(s1->posnum, s2)) { + new1 = (Pset) new_node(new1); + if (new1 == NULL) return NULL; + new1->posnum = s1->posnum; + if (hd == NULL) hd = new1; + else curr->nextpos = new1; + } + curr = new1; + s1 = s1->nextpos; + } + if (hd == NULL) hd = s2; + else curr->nextpos = s2; + return hd; + } + + /* create_pos() creates a position node with the position value given, + then returns a pointer to this node. */ + + Pset create_pos(int n) + { + Pset x; + + x = (Pset) new_node(x); + if (x == NULL) return NULL; + x->posnum = n; + x->nextpos = NULL; + return x; + } + + /* eq_pset() takes two position sets and checks to see if they are + equal. It returns 1 if the sets are equal, 0 if they are not. */ + + int subset_pset(Pset s1, Pset s2) + { + int subs = 1; + + while (s1 != NULL && subs != 0) { + subs = 0; + while (s2 != NULL && subs != 1) + if (s1->posnum == s2->posnum) subs = 1; + else s2 = s2->nextpos; + s1 = s1->nextpos; + } + return subs; + } + + int eq_pset(Pset s1, Pset s2) + { + return subset_pset(s1, s2) && subset_pset(s2, s1); + } + From lattner at cs.uiuc.edu Tue Oct 5 13:03:19 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:03:19 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/README.txt Message-ID: <200410051803.NAA20611@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C: README.txt added (r1.1) --- Log message: new suite --- Diffs of the changes: (+3 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/README.txt diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/README.txt:1.1 *** /dev/null Tue Oct 5 13:03:18 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/README.txt Tue Oct 5 13:03:08 2004 *************** *** 0 **** --- 1,3 ---- + These benchmarks were downloaded from: + http://www.prolangs.rutgers.edu/public.html + From gaeke at cs.uiuc.edu Tue Oct 5 13:04:51 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Tue, 5 Oct 2004 13:04:51 -0500 Subject: [llvm-commits] CVS: llvm/examples/BFtoLLVM/ Message-ID: <200410051804.NAA05035@zion.cs.uiuc.edu> Changes in directory llvm/examples/BFtoLLVM: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm/examples/BFtoLLVM added to the repository --- Diffs of the changes: (+0 -0) From gaeke at cs.uiuc.edu Tue Oct 5 13:05:04 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Tue, 5 Oct 2004 13:05:04 -0500 Subject: [llvm-commits] CVS: llvm/examples/BFtoLLVM/tests/ Message-ID: <200410051805.NAA05077@zion.cs.uiuc.edu> Changes in directory llvm/examples/BFtoLLVM/tests: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm/examples/BFtoLLVM/tests added to the repository --- Diffs of the changes: (+0 -0) From gaeke at cs.uiuc.edu Tue Oct 5 13:05:36 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Tue, 5 Oct 2004 13:05:36 -0500 Subject: [llvm-commits] CVS: llvm/examples/BFtoLLVM/tests/Makefile hello.b hello.expected-out Message-ID: <200410051805.NAA05168@zion.cs.uiuc.edu> Changes in directory llvm/examples/BFtoLLVM/tests: Makefile added (r1.1) hello.b added (r1.1) hello.expected-out added (r1.1) --- Log message: Add BFtoLLVM example front end --- Diffs of the changes: (+51 -0) Index: llvm/examples/BFtoLLVM/tests/Makefile diff -c /dev/null llvm/examples/BFtoLLVM/tests/Makefile:1.1 *** /dev/null Tue Oct 5 13:05:36 2004 --- llvm/examples/BFtoLLVM/tests/Makefile Tue Oct 5 13:05:26 2004 *************** *** 0 **** --- 1,45 ---- + ##===- examples/BFtoLLVM/tests/Makefile --------------------*- Makefile -*-===## + # + # The LLVM Compiler Infrastructure + # + # This file was developed by the LLVM research group and is distributed under + # the University of Illinois Open Source License. See LICENSE.TXT for details. + # + ##===----------------------------------------------------------------------===## + + # Makefile for bf2llvm tests. + + LEVEL = ../../.. + BFTOLLVM = $(LLVMTOOLCURRENT)/BFtoLLVM + + include $(LEVEL)/Makefile.common + + all:: check + + clean:: + rm -rf Output + + .SUFFIXES: .ll .gccas.bc .llvm .cbe.c .cbe + + Output/%.ll: %.b $(BFTOLLVM) Output/.dir + $(BFTOLLVM) $< $@ + + Output/%.gccas.bc: Output/%.ll Output/.dir + $(LGCCAS) $< -o $@ + + Output/%.llvm Output/%.llvm.bc: Output/%.gccas.bc Output/.dir + $(LGCCLD) $< -lc -lcrtend -o Output/$*.llvm + + Output/%.cbe.c: Output/%.llvm.bc Output/.dir + $(LLC) -march=c -f -o=$@ $< + + Output/%.cbe: Output/%.cbe.c Output/.dir + $(CC) -O2 $< -o $@ + + check: Output/hello.cbe hello.expected-out + @echo "Running test" + Output/hello.cbe > Output/hello.out-cbe + @echo "Checking result" + diff Output/hello.out-cbe hello.expected-out + @echo "Test passed" + Index: llvm/examples/BFtoLLVM/tests/hello.b diff -c /dev/null llvm/examples/BFtoLLVM/tests/hello.b:1.1 *** /dev/null Tue Oct 5 13:05:36 2004 --- llvm/examples/BFtoLLVM/tests/hello.b Tue Oct 5 13:05:26 2004 *************** *** 0 **** --- 1,5 ---- + Hello World program + >+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]>++++++++[<++++>-] + <.#>+++++++++++[<+++++>-]<.>++++++++[<+++>-]<.+++.------.--------.[-]>++++++++[ + <++++>-]<+.[-]++++++++++. + Index: llvm/examples/BFtoLLVM/tests/hello.expected-out diff -c /dev/null llvm/examples/BFtoLLVM/tests/hello.expected-out:1.1 *** /dev/null Tue Oct 5 13:05:36 2004 --- llvm/examples/BFtoLLVM/tests/hello.expected-out Tue Oct 5 13:05:26 2004 *************** *** 0 **** --- 1 ---- + Hello World! From gaeke at cs.uiuc.edu Tue Oct 5 13:05:37 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Tue, 5 Oct 2004 13:05:37 -0500 Subject: [llvm-commits] CVS: llvm/examples/BFtoLLVM/BFtoLLVM.cpp Makefile Message-ID: <200410051805.NAA05173@zion.cs.uiuc.edu> Changes in directory llvm/examples/BFtoLLVM: BFtoLLVM.cpp added (r1.1) Makefile added (r1.1) --- Log message: Add BFtoLLVM example front end --- Diffs of the changes: (+220 -0) Index: llvm/examples/BFtoLLVM/BFtoLLVM.cpp diff -c /dev/null llvm/examples/BFtoLLVM/BFtoLLVM.cpp:1.1 *** /dev/null Tue Oct 5 13:05:36 2004 --- llvm/examples/BFtoLLVM/BFtoLLVM.cpp Tue Oct 5 13:05:26 2004 *************** *** 0 **** --- 1,208 ---- + //===-- BFtoLLVM.cpp - BF language Front End for LLVM ---------------------===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by the LLVM research group and is distributed under + // the University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This is a simple front end for the BF language. It is compatible with the + // language as described in "The BrainF*** Language Specification (01 January + // 2002)", which is available from http://esoteric.sange.fi/ENSI . It does not + // implement the optional keyword # ("Output partial tape state"). + // + //===----------------------------------------------------------------------===// + + #include + #include + #include + #include + #include + #include + #include + #include + + void emitDeclarations(std::ofstream &dest) { + dest << "; This assembly code brought to you by BFtoLLVM\n" + << "\nimplementation\n" + << "\n; Declarations\n" + << "\ndeclare int %getchar()\n" + << "declare int %putchar(int)\n" + << "declare void %llvm.memset(sbyte*, ubyte, uint, uint)\n" + << "\n"; + } + + void emitMainFunctionProlog(std::ofstream &dest) { + dest << "\n; Main function\n" + << "int %main(int %argc, sbyte** %argv) {\n" + << "\nentry:\n" + << "%arr = alloca sbyte, uint 30000\n" + << "call void (sbyte*, ubyte, uint, uint)* %llvm.memset(sbyte* %arr, ubyte 0, uint 30000, uint 1)\n" + << "%ptrbox = alloca sbyte*\n" + << "store sbyte* %arr, sbyte **%ptrbox\n" + << "\n"; + } + + void emitMainFunctionEpilog(std::ofstream &dest) { + dest << "ret int 0\n" + << "}\n"; + } + + std::string gensym (const std::string varName, bool percent = true) { + char buf[80]; + static unsigned int SymbolCounter = 0; + sprintf (buf, "%s%s%u", percent ? "%" : "", varName.c_str(), SymbolCounter++); + return std::string (buf); + } + + void emitArith (std::string op, char delta, std::ofstream &dest) { + std::string ptr = gensym (op + "ptr"), + val = gensym (op + "val"), + result = gensym (op + "result"); + dest << ptr << " = load sbyte** %ptrbox\n" + << val << " = load sbyte* " << ptr << "\n" + << result << " = add sbyte " << val << ", " << (int)delta << "\n" + << "store sbyte " << result << ", sbyte* " << ptr << "\n"; + } + + // + becomes ++*p; and - becomes --*p; + void emitPlus (std::ofstream &dest, int ct) { emitArith ("plus", +ct, dest); } + void emitMinus (std::ofstream &dest, int ct) { emitArith ("minus", -ct, dest); } + + void emitLoadAndCast (std::string ptr, std::string val, std::string cast, + std::string type, std::ofstream &dest) { + dest << ptr << " = load sbyte** %ptrbox\n" + << val << " = load sbyte* " << ptr << "\n" + << cast << " = cast sbyte " << val << " to " << type << "\n"; + } + + // , becomes *p = getchar(); + void emitComma(std::ofstream &dest, int ct) { + assert (ct == 1); + std::string ptr = gensym("commaptr"), read = gensym("commaread"), + cast = gensym("commacast"); + dest << ptr << " = load sbyte** %ptrbox\n" + << read << " = call int %getchar()\n" + << cast << " = cast int " << read << " to sbyte\n" + << "store sbyte " << cast << ", sbyte* " << ptr << "\n"; + } + + // . becomes putchar(*p); + void emitDot(std::ofstream &dest, int ct) { + assert (ct == 1); + std::string ptr = gensym("dotptr"), val = gensym("dotval"), + cast = gensym("dotcast"); + emitLoadAndCast (ptr, val, cast, "int", dest); + dest << "call int %putchar(int " << cast << ")\n"; + } + + void emitPointerArith(std::string opname, int delta, std::ofstream &dest) { + std::string ptr = gensym(opname + "ptr"), result = gensym(opname + "result"); + dest << ptr << " = load sbyte** %ptrbox\n" + << result << " = getelementptr sbyte* " << ptr << ", int " << delta + << "\n" + << "store sbyte* " << result << ", sbyte** %ptrbox\n"; + } + + // < becomes --p; and > becomes ++p; + void emitLT(std::ofstream &dest, int ct) { emitPointerArith ("lt", -ct, dest); } + void emitGT(std::ofstream &dest, int ct) { emitPointerArith ("gt", +ct, dest); } + + static std::vector whileStack; + + // [ becomes while (*p) { + void emitLeftBracket(std::ofstream &dest, int ct) { + assert (ct == 1); + std::string whileName = gensym ("While", false); + whileStack.push_back (whileName); + dest << "br label %testFor" << whileName << "\n" + << "\ninside" << whileName << ":\n"; + } + + // ] becomes } + void emitRightBracket(std::ofstream &dest, int ct) { + assert (ct == 1); + std::string whileName = whileStack.back (), + ptr = gensym("bracketptr"), + val = gensym("bracketval"), + cast = gensym("bracketcast"); + whileStack.pop_back (); + dest << "br label %testFor" << whileName << "\n" + << "\ntestFor" << whileName << ":\n"; + emitLoadAndCast (ptr, val, cast, "bool", dest); + dest << "br bool " << cast << ", label %inside" << whileName << ", " + << "label %after" << whileName << "\n" + << "\nafter" << whileName << ":\n"; + } + + typedef void (*FuncTy)(std::ofstream &, int); + static FuncTy table[256]; + static bool multi[256]; + + void consume (int ch, int repeatCount, std::ofstream &dest) { + FuncTy func = table[ch]; + if (!func) + return; + else if (multi[ch]) + func (dest, repeatCount); + else + for (int i = 0; i < repeatCount; ++i) + func (dest, 1); + } + + void initializeTable() { + memset (table, 0, 256); + memset (multi, 0, 256); + table[(int)'+'] = emitPlus; multi[(int)'+'] = true; + table[(int)'-'] = emitMinus; multi[(int)'-'] = true; + table[(int)','] = emitComma; multi[(int)','] = false; + table[(int)'.'] = emitDot; multi[(int)'.'] = false; + table[(int)'<'] = emitLT; multi[(int)'<'] = true; + table[(int)'>'] = emitGT; multi[(int)'>'] = true; + table[(int)'['] = emitLeftBracket; multi[(int)'['] = false; + table[(int)']'] = emitRightBracket; multi[(int)']'] = false; + } + + int main (int argc, char **argv) { + if (argc != 3) { + std::cerr << "usage: " << argv[0] << " input-source output-llvm\n"; + return 1; + } + + char *sourceFileName = argv[1]; + char *destFileName = argv[2]; + + std::ifstream src (sourceFileName); + if (!src.good()) { + std::cerr << sourceFileName << ": " << strerror(errno) << "\n"; + return 1; + } + + std::ofstream dest (destFileName); + if (!dest.good()) { + std::cerr << destFileName << ": " << strerror(errno) << "\n"; + return 1; + } + + emitDeclarations(dest); + emitMainFunctionProlog(dest); + + initializeTable(); + char ch, lastCh; + src >> lastCh; + int repeatCount = 1; + for (src >> ch; !src.eof (); src >> ch, ++repeatCount) + if (ch != lastCh) { + consume (lastCh, repeatCount, dest); + lastCh = ch; + repeatCount = 0; + } + consume (lastCh, repeatCount, dest); + + emitMainFunctionEpilog(dest); + + src.close(); + dest.close(); + return 0; + } Index: llvm/examples/BFtoLLVM/Makefile diff -c /dev/null llvm/examples/BFtoLLVM/Makefile:1.1 *** /dev/null Tue Oct 5 13:05:36 2004 --- llvm/examples/BFtoLLVM/Makefile Tue Oct 5 13:05:26 2004 *************** *** 0 **** --- 1,12 ---- + ##===- examples/BFtoLLVM/Makefile --------------------------*- Makefile -*-===## + # + # The LLVM Compiler Infrastructure + # + # This file was developed by the LLVM research group and is distributed under + # the University of Illinois Open Source License. See LICENSE.TXT for details. + # + ##===----------------------------------------------------------------------===## + + LEVEL = ../.. + TOOLNAME = BFtoLLVM + include $(LEVEL)/Makefile.common From gaeke at cs.uiuc.edu Tue Oct 5 13:06:04 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Tue, 5 Oct 2004 13:06:04 -0500 Subject: [llvm-commits] CVS: llvm/examples/Makefile Message-ID: <200410051806.NAA05260@zion.cs.uiuc.edu> Changes in directory llvm/examples: Makefile updated: 1.4 -> 1.5 --- Log message: Build BFtoLLVM example front-end by default --- Diffs of the changes: (+1 -1) Index: llvm/examples/Makefile diff -u llvm/examples/Makefile:1.4 llvm/examples/Makefile:1.5 --- llvm/examples/Makefile:1.4 Mon Aug 23 14:29:54 2004 +++ llvm/examples/Makefile Tue Oct 5 13:05:53 2004 @@ -11,6 +11,6 @@ include $(LEVEL)/Makefile.config #PARALLEL_DIRS:= $(patsubst %/Makefile,%,$(wildcard $(SourceDir)/*/Makefile)) -PARALLEL_DIRS:= Fibonacci HowToUseJIT ModuleMaker +PARALLEL_DIRS:= Fibonacci HowToUseJIT ModuleMaker BFtoLLVM include $(LEVEL)/Makefile.common From lattner at cs.uiuc.edu Tue Oct 5 13:08:17 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:08:17 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/ Message-ID: <200410051808.NAA20831@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 13:09:12 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:09:12 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/Output/ Message-ID: <200410051809.NAA20993@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/Output: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/Output added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 13:09:29 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:09:29 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/Makefile all.c horners.c horners.h newton.c newton.h values.h Message-ID: <200410051809.NAA21022@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots: Makefile added (r1.1) all.c added (r1.1) horners.c added (r1.1) horners.h added (r1.1) newton.c added (r1.1) newton.h added (r1.1) values.h added (r1.1) --- Log message: new benchmark --- Diffs of the changes: (+212 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/Makefile:1.1 *** /dev/null Tue Oct 5 13:09:26 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/Makefile Tue Oct 5 13:09:16 2004 *************** *** 0 **** --- 1,7 ---- + LEVEL = ../../../.. + + PROG = allroots + LDFLAGS = -lm + #RUN_OPTIONS = -2 int $(BUILD_SRC_DIR)/InstructionCombining.cpp.txt + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/all.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/all.c:1.1 *** /dev/null Tue Oct 5 13:09:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/all.c Tue Oct 5 13:09:16 2004 *************** *** 0 **** --- 1,131 ---- + #include + #include + #include + #include "newton.h" + #include "horners.h" + #include "values.h" + + extern void allroots(int No,double Po[],int N,double Pn[]); + extern void deflat(int No,double Po[],int N,double Pn[],double ROOT); + + int main(void) { + static double A[] = {4.1,-3.9,-1.0,1.0}; + int N = 3; + int J; + printf("DEBUG: %g %g\n",2.69065*2.69065*2.69065,2.69065*2.69065); + printf("==============================================================\n"); + printf("Find all roots of\n"); + + for (J=N;J>0;J--) { + printf("%g",d_abs(A[J])); + if (A[J-1] < 0) + printf("x**%d - ",J); + else + printf("x**%d + ",J); + } + + printf("%g\n",d_abs(A[0])); + printf("using NEWTON method.\n"); + printf("==============================================================\n"); + allroots(N,A,N,A); + return 0; + } + + void allroots(int No,double Po[],int N,double Pn[]) + + /* Computes the Maximum interval that all the roots for the polynomial P + can contain with |root| < |P[0]| + |P[1]| + ... + |P[n]| \ |P[n]| where + P[i] is the coefficent of the Ith degree of the polynomial + + Next it looks for a change of sign of F(x) on the range, when it finds one + it calls a METHOD for finding an individual root and then repeats the + process with the range now starting just after the last found root */ + + { + int I; /* counter */ + double ROOT; + + double LOWER,UPPER; /* lower and upperbound of all roots of P */ + + + UPPER = 0; + for (I=0;I<=N;I++) + UPPER += d_abs(Pn[I]); + + UPPER /= d_abs(Pn[N]); + LOWER = -UPPER - 1.0; + + if (N == 0) + printf("No roots\n"); + else + if (N == 1) { + ROOT = -Pn[0]/Pn[1]; + printf(" ROOT = %g\n",ROOT); + } + else + if (N == 2) { + ROOT = (-Pn[1] + sqrt(Pn[1]*Pn[1] - 4*Pn[2]*Pn[0]))/(2*Pn[2]); + printf(" ROOT = %g (from quadratic formula)\n",ROOT); + ROOT = (-Pn[1] - sqrt(Pn[1]*Pn[1] - 4*Pn[2]*Pn[0]))/(2*Pn[2]); + printf(" ROOT = %g (from quadratic formula)\n",ROOT); + } + else { + ROOT = newton(N,Pn,LOWER,UPPER); + deflat(No,Po,N,Pn,ROOT); + } + } + + + void deflat(int No,double Po[],int N,double Pn[],double ROOT) + { + double *TP; + int I,J; + + if (N != No) { + printf("----> Refine Root on the Orginal Polynomial (non-deflated)\n"); + newton(No,Po,ROOT-.5,ROOT+.5); + } + + TP = (double *) calloc(N,sizeof(ROOT)); + + TP[N-1]=Pn[N]; + for (I=N-2;I>=0;I--) + TP[I] = TP[I+1]*ROOT+Pn[I+1]; + + for (J=N;J>0;J--) { + printf("%g",d_abs(Pn[J])); + if (Pn[J-1] < 0) + printf("x**%d - ",J); + else + printf("x**%d + ",J); + } + + printf("%g\n",d_abs(Pn[0])); + printf(" DEFLATED to\n(x - %g)*(",ROOT); + + for (J=N-1;J>0;J--) { + printf("%g",d_abs(TP[J])); + if (TP[J-1] < 0) + printf("x**%d - ",J); + else + printf("x**%d + ",J); + } + + printf("%g)\n",d_abs(TP[0])); + + if (N == 3) { + ROOT = (-TP[1] + sqrt(TP[1]*TP[1] - 4*TP[2]*TP[0]))/(2*TP[2]); + printf("\n ROOT = %g (from quadratic formula)\n",ROOT); + printf("----> Refine Root on the Orginal Polynomial (non-deflated)\n"); + newton(No,Po,ROOT-.5,ROOT+.5); + + ROOT = (-TP[1] - sqrt(TP[1]*TP[1] - 4*TP[2]*TP[0]))/(2*TP[2]); + printf(" ROOT = %g (from quadratic formula)\n",ROOT); + printf("----> Refine Root on the Orginal Polynomial (non-deflated)\n"); + newton(No,Po,ROOT-.5,ROOT+.5); + } + else { + allroots(No,Po,N-1,TP); + } + free(TP); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/horners.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/horners.c:1.1 *** /dev/null Tue Oct 5 13:09:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/horners.c Tue Oct 5 13:09:16 2004 *************** *** 0 **** --- 1,31 ---- + double DERIV_X; /* Global Var: HORNERS function has the side effect + of setting DERIV_X to the derivative of polynomial + at X */ + + double HORNERS(int DEGREE,double COEF[],double X) + + /* Algo. 2.6 (pp. 68 - 69) of NUMERICAL ANALYSIS by Richard Burden and + J. Douglas Faires */ + { + double P_X; /* Value of the polynomial at X */ + double dP_X; /* Value of the derivative of the polynomial at X */ + int J; /* a counter variable */ + + P_X = dP_X = COEF[DEGREE]; + + for (J = DEGREE - 1; J >= 1; J --) { + P_X = X*P_X + COEF[J]; + dP_X = X*dP_X + P_X; + } + + P_X = X*P_X + COEF[0]; + + DERIV_X = dP_X; + return P_X; + } + + double d_abs(double D) + { + if (D < 0) D = -1.0*D; + return D; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/horners.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/horners.h:1.1 *** /dev/null Tue Oct 5 13:09:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/horners.h Tue Oct 5 13:09:16 2004 *************** *** 0 **** --- 1,3 ---- + extern double DERIV_X; + extern double HORNERS(int DEGREE,double COEF[],double X); + extern double d_abs(double D); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/newton.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/newton.c:1.1 *** /dev/null Tue Oct 5 13:09:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/newton.c Tue Oct 5 13:09:16 2004 *************** *** 0 **** --- 1,32 ---- + #include "values.h" + #include "horners.h" + #include + + + double newton (int N,double P[],double A,double B) + { + double T_DOUBLE; /* for temporary storage */ + double Xk,Xk1; /* the kth and k+1rst quess at the root */ + int K = 0; /* number of iterations so far */ + + /* make sure that A is lower bound of the interval and B is the upper bound */ + if (B < A) { + T_DOUBLE = A; + A = B; + B = T_DOUBLE; + } + + printf(" NEWTON Called on interval [%g,%g]\n",A,B); + Xk = A; + Xk1 = (A + B)/2; /* initial quess is the midpoint of the interval */ + + while ( (d_abs(Xk1-Xk)/d_abs(Xk1) > Episolon_n) && K <= MAX_1 ) { + printf(" X[%d] = %g\n",K+1,Xk1); + Xk = Xk1; + Xk1 = Xk1 - HORNERS(N,P,Xk1)/DERIV_X; + K ++; + } + printf("ROOT: %g (approx.)\n\n",Xk1); + return Xk1; + } + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/newton.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/newton.h:1.1 *** /dev/null Tue Oct 5 13:09:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/newton.h Tue Oct 5 13:09:16 2004 *************** *** 0 **** --- 1 ---- + extern double newton (int N,double P[],double A,double B); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/values.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/values.h:1.1 *** /dev/null Tue Oct 5 13:09:29 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/allroots/values.h Tue Oct 5 13:09:16 2004 *************** *** 0 **** --- 1,7 ---- + /* tollerance of stopping criteron */ + #define Episolon_n 0.5E-5 + #define Episolon_b 0.5E-1 + #define Episolon_sec 0.5E-5 + #define MAX_1 40 + + #define Increment 0.49E-1 From lattner at cs.uiuc.edu Tue Oct 5 13:19:47 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:19:47 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/ Message-ID: <200410051819.NAA21683@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 13:20:09 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:20:09 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/Makefile aquery.c archie.c archie.h atalloc.c copyright.h dirsend.c get_pauth.c get_vdir.c patchlevel.h pauthent.h pcompat.h perrmesg.c perrno.h pfs.h pmachine.h pprot.h procquery.c ptalloc.c rdgram.h regex.c regex.h stcopy.c support.c vl_comp.c vlalloc.c vms.h Message-ID: <200410051820.NAA21753@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client: Makefile added (r1.1) aquery.c added (r1.1) archie.c added (r1.1) archie.h added (r1.1) atalloc.c added (r1.1) copyright.h added (r1.1) dirsend.c added (r1.1) get_pauth.c added (r1.1) get_vdir.c added (r1.1) patchlevel.h added (r1.1) pauthent.h added (r1.1) pcompat.h added (r1.1) perrmesg.c added (r1.1) perrno.h added (r1.1) pfs.h added (r1.1) pmachine.h added (r1.1) pprot.h added (r1.1) procquery.c added (r1.1) ptalloc.c added (r1.1) rdgram.h added (r1.1) regex.c added (r1.1) regex.h added (r1.1) stcopy.c added (r1.1) support.c added (r1.1) vl_comp.c added (r1.1) vlalloc.c added (r1.1) vms.h added (r1.1) --- Log message: New "Benchmark". Of course running it just prints usage info, but whatever. --- Diffs of the changes: (+5517 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/Makefile:1.1 *** /dev/null Tue Oct 5 13:20:08 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/Makefile Tue Oct 5 13:19:57 2004 *************** *** 0 **** --- 1,5 ---- + LEVEL = ../../../.. + + PROG = archie + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/aquery.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/aquery.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/aquery.c Tue Oct 5 13:19:57 2004 *************** *** 0 **** --- 1,257 ---- + /* + * aquery.c : Programmatic Prospero interface to Archie + * + * Copyright (c) 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + * + * Originally part of the Prospero Archie client by Clifford + * Neuman (bcn at isi.edu). Modifications, addition of programmatic interface, + * and new sorting code by George Ferguson (ferguson at cs.rochester.edu) + * and Brendan Kehoe (brendan at cs.widener.edu). MSDOS and OS2 modifications + * to use with PC/TCP by Mark Towfiq (towfiq at FTP.COM). + * + * v1.2.1 - 11/19/91 (mmt) - added MSDOS & OS2 stuff + * v1.2.0 - 09/17/91 (bpk) - added BULL & USG stuff, thanks to Jim Sillas + * v1.1.3 - 08/30/91 (bpk) - cast index() + * v1.1.2 - 08/20/91 (bcn) - make it do it properly (new invdatecmplink) + * v1.1.1 - 08/20/91 (bpk) - made sorting go inverted as we purport it does + */ + #include + + #include + + #include + #include + #include + + #include + #ifdef NEED_STRING_H + # include /* for char *index() */ + #else + # include /* for char *index() */ + #endif + + static void translateArchieResponse(); + + extern int pwarn; + extern char p_warn_string[]; + + /* + * archie_query : Sends a request to _host_, telling it to search for + * _string_ using _query_type_ as the search method. + * No more than _max_hits_ matches are to be returned + * skipping over _offset_ matches. + * + * archie_query returns a linked list of virtual links. + * If _flags_ does not include AQ_NOTRANS, then the Archie + * responses will be translated. If _flags_ does not include + * AQ_NOSORT, then the list will be sorted using _cmp_proc_ to + * compare pairs of links. If _cmp_proc_ is NULL or AQ_DEFCMP, + * then the default comparison procedure, defcmplink(), is used + * sorting by host, then filename. If cmp_proc is AQ_INVDATECMP + * then invdatecmplink() is used, sorting inverted by date. + * otherwise a user-defined comparison procedure is called. + * + * archie_query returns NULL and sets perrno if the query + * failed. Note that it can return NULL with perrno == PSUCCESS + * if the query didn't fail but there were simply no matches. + * + * query_type: S Substring search ignoring case + * C Substring search with case significant + * R Regular expression search + * = Exact String Match + * s,c,e Tries exact match first and falls back to S, C, or R + * if not found. + * + * cmp_proc: AQ_DEFCMP Sort by host, then filename + * AQ_INVDATECMP Sort inverted by date + * + * flags: AQ_NOSORT Don't sort results + * AQ_NOTRANS Don't translate results + */ + + extern void bzero(char *b,int length); + extern int get_vdir(char *dhost,char *dfile,char *components,VDIR1 dir, + long flags,VLINK filters,char *acomp); + + VLINK archie_query(char *host,char *string,int max_hits,int offset, + char query_type,int (*cmp_proc)(),int flags) + { + char qstring[MAX_VPATH]; /* For construting the query */ + VLINK links; /* Matches returned by server */ + VDIR_ST dir_st; /* Filled in by get_vdir */ + VDIR1 dir= &dir_st; + + VLINK p,q,r,lowest,nextp,pnext,pprev; + int tmp; + + /* Set the cmp_proc if not given */ + if (cmp_proc == NULL) cmp_proc = defcmplink; + + /* Make the query string */ + sprintf(qstring,"ARCHIE/MATCH(%d,%d,%c)/%s", + max_hits,offset,query_type,string); + + /* Initialize Prospero structures */ + perrno = PSUCCESS; *p_err_string = '\0'; + pwarn = PNOWARN; *p_warn_string = '\0'; + vdir_init(dir); + + /* Retrieve the list of matches, return error if there was one */ + #if defined(MSDOS) + if(tmp = get_vdir(host, qstring, "", dir, (long)GVD_ATTRIB|GVD_NOSORT, + NULL, NULL)) { + #else + if((tmp = get_vdir(host,qstring,"",dir,GVD_ATTRIB|GVD_NOSORT,NULL,NULL))) { + # endif + perrno = tmp; + return(NULL); + } + + /* Save the links, and clear in dir in case it's used again */ + links = dir->links; dir->links = NULL; + + /* As returned, list is sorted by suffix, and conflicting */ + /* suffixes appear on a list of "replicas". We want to */ + /* create a one-dimensional list sorted by host then filename */ + /* and maybe by some other parameter */ + + /* First flatten the doubly-linked list */ + for (p = links; p != NULL; p = nextp) { + nextp = p->next; + if (p->replicas != NULL) { + p->next = p->replicas; + p->next->previous = p; + for (r = p->replicas; r->next != NULL; r = r->next) + /*EMPTY*/ ; + r->next = nextp; + nextp->previous = r; + p->replicas = NULL; + } + } + + /* Translate the filenames unless NOTRANS was given */ + if (!(flags & AQ_NOTRANS)) + for (p = links; p != NULL; p = p->next) + translateArchieResponse(p); + + /* If NOSORT given, then just hand it back */ + if (flags & AQ_NOSORT) { + perrno = PSUCCESS; + return(links); + } + + /* Otherwise sort it using a selection sort and the given cmp_proc */ + for (p = links; p != NULL; p = nextp) { + nextp = p->next; + lowest = p; + for (q = p->next; q != NULL; q = q->next) + if ((*cmp_proc)(q,lowest) < 0) + lowest = q; + if (p != lowest) { + /* swap the two links */ + pnext = p->next; + pprev = p->previous; + if (lowest->next != NULL) + lowest->next->previous = p; + p->next = lowest->next; + if (nextp == lowest) { + p->previous = lowest; + } else { + lowest->previous->next = p; + p->previous = lowest->previous; + } + if (nextp == lowest) { + lowest->next = p; + } else { + pnext->previous = lowest; + lowest->next = pnext; + } + if (pprev != NULL) + pprev->next = lowest; + lowest->previous = pprev; + /* keep the head of the list in the right place */ + if (links == p) + links = lowest; + } + } + + /* Return the links */ + perrno = PSUCCESS; + return(links); + } + + /* + * translateArchieResponse: + * + * If the given link is for an archie-pseudo directory, fix it. + * This is called unless AQ_NOTRANS was given to archie_query(). + */ + static void translateArchieResponse(VLINK l) + { + char *slash; + + if (strcmp(l->type,"DIRECTORY") == 0) { + if (strncmp(l->filename,"ARCHIE/HOST",11) == 0) { + l->type = stcopyr("EXTERNAL(AFTP,DIRECTORY)",l->type); + l->host = stcopyr(l->filename+12,l->host); + /* + slash = (char *)index(l->host,'/'); + */ + slash = strchr(l->host,(int) '/'); + if (slash) { + l->filename = stcopyr(slash,l->filename); + *slash++ = '\0'; + } else + l->filename = stcopyr("",l->filename); + } + } + } + + /* + * defcmplink: The default link comparison function for sorting. Compares + * links p and q first by host then by filename. Returns < 0 if p + * belongs before q, > 0 if p belongs after q, and == 0 if their + * host and filename fields are identical. + */ + + int defcmplink(VLINK p,VLINK q) + { + int result; + + if ((result=strcmp(p->host,q->host)) != 0) + return(result); + else + return(strcmp(p->filename,q->filename)); + } + + /* + * invdatecmplink: An alternative comparison function for sorting that + * compares links p and q first by LAST-MODIFIED date, + * if they both have that attribute. If both links + * don't have that attribute or the dates are the + * same, it then calls defcmplink() and returns its + * value. + */ + + int invdatecmplink(VLINK p,VLINK q) + { + PATTRIB pat,qat; + char *pdate,*qdate; + int result; + + pdate = qdate = NULL; + for (pat = p->lattrib; pat; pat = pat->next) + if(strcmp(pat->aname,"LAST-MODIFIED") == 0) + pdate = pat->value.ascii; + for (qat = q->lattrib; qat; qat = qat->next) + if(strcmp(qat->aname,"LAST-MODIFIED") == 0) + qdate = qat->value.ascii; + if(!pdate && !qdate) return(defcmplink(p,q)); + if(!pdate) return(1); + if(!qdate) return(-1); + if((result=strcmp(qdate,pdate)) == 0) return(defcmplink(p,q)); + else return(result); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/archie.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/archie.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/archie.c Tue Oct 5 13:19:57 2004 *************** *** 0 **** --- 1,290 ---- + /* + * Copyright (c) 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + * + * v1.2.1 - 11/21/91 (bkc) - added CUTCP library support for MSDOS + * v1.2.0 - 11/19/91 (mmt) - added MSDOS & OS2 stuff + * v1.1.2 - 08/27/91 (bpk) - added for index() + * v1.1.1 - 08/22/91 (bpk) - added 0-9 as arguments + */ + + #include + #include + + /* + * Archie client using the Prospero protocol. + * + * Suggestions and improvements to Brendan Kehoe (brendan at cs.widener.edu). + */ + + #include + #if defined(OS2) + # include + #endif + #ifdef MSDOS + # include + # include + # ifdef CUTCP + # include + # include + # endif + #endif + + #include + #include + #include + #include + + int listflag = 0; + int sortflag = 0; /* 1 = by date */ + char *progname; + #ifdef DEBUG + extern int pfs_debug; + #endif + extern int rdgram_priority; + + /* To keep the code clean.. */ + #ifdef VMS + # define NFLAG "\"N\"" + # define LFLAG "\"L\"" + # define A_EXIT SS$_NORMAL + #else + # define NFLAG "N" + # define LFLAG "L" + # define A_EXIT 1 + #endif + #ifdef CUTCP + # define HFLAG "[H config.tel]]" + #else + # define HFLAG "]" + #endif + + #define ARCHIE_HOST "archie.rutgers.edu" + + void main(int argc,char *argv[]) + { + char *cur_arg; + char qtype = '='; /* Default to exact string match */ + char etype = '='; /* Type if only -e is specified */ + int eflag = 0; /* Exact flag specified */ + int max_hits = MAX_HITS; + int offset = 0; + int exitflag = 0; /* Display release identifier */ + int tmp; + char *host = ARCHIE_HOST; + char *p; + static char *archies[] = { ARCHIES }; + #ifdef CUTCP + int hostset = 0; + #endif + char *getenv(); + + progname = "archie"; + argc--; argv++; + + #ifdef CUTCP + if(getenv("CONFIGTEL")) + if(Shostfile(getenv("CONFIGTEL")) < 0) { + fprintf(stderr,"Error, couldn't open configtel file %s\n", + getenv("CONFIGTEL")); + exit(1); + } + #endif + + if ((p = getenv("ARCHIE_HOST")) != (char *)NULL) + host = p; + + while (argc > 0 && **argv == '-') { + cur_arg = argv[0]+1; + + /* If a - by itself, or --, then no more arguments */ + if(!*cur_arg || ((*cur_arg == '-') && (!*(cur_arg+1)))) { + argc--, argv++; + goto scandone; + } + + while (*cur_arg) { + switch (*cur_arg++) { + #ifdef DEBUG + case 'D': /* Debug level */ + pfs_debug = 1; /* Default debug level */ + if(*cur_arg && strchr("0123456789",(int) *cur_arg)) { + sscanf(cur_arg,"%d",&pfs_debug); + cur_arg += strspn(cur_arg,"0123456789"); + } + else if(argc > 2) { + tmp = sscanf(argv[1],"%d",&pfs_debug); + if (tmp == 1) {argc--;argv++;} + } + break; + #endif + #ifdef CUTCP + case 'H' : + if(Shostfile(argv[1]) < 0) { + fprintf(stderr,"Error, couldn't open configtel file %s\n",argv[1]); + exit(1); + } + argc--;argv++; + break; + #endif + #ifndef XARCHIE + case 'L': + printf("Known archie servers:\n"); + for (tmp = 0; tmp < NARCHIES; tmp++) + printf("\t%s\n", archies[tmp]); + printf(" * %s is the default Archie server.\n", ARCHIE_HOST); + printf(" * For the most up-to-date list, write to an Archie server and give it\n the command `servers'.\n"); + exitflag = 1; + break; + #endif + + case 'N': /* Priority (nice) */ + rdgram_priority = RDGRAM_MAX_PRI; /* Use this if no # */ + if(*cur_arg && strchr("-0123456789",(int) *cur_arg)) { + sscanf(cur_arg,"%d",&rdgram_priority); + cur_arg += strspn(cur_arg,"-0123456789"); + } + else if(argc > 2) { + tmp = sscanf(argv[1],"%d",&rdgram_priority); + if (tmp == 1) {argc--;argv++;} + } + if(rdgram_priority > RDGRAM_MAX_SPRI) + rdgram_priority = RDGRAM_MAX_PRI; + if(rdgram_priority < RDGRAM_MIN_PRI) + rdgram_priority = RDGRAM_MIN_PRI; + break; + + case 'c': /* substring (case sensitive) */ + qtype = 'C'; + etype = 'c'; + break; + + case 'e': /* Exact match */ + /* If -e specified by itself, then we use the */ + /* default value of etype which must be '=' */ + eflag++; + break; + + case 'h': /* Host */ + host = argv[1]; + #ifdef CUTCP + hostset++; + #endif + argc--; argv++; + break; + + case 'l': /* List one match per line */ + listflag++; + break; + + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + cur_arg--; + case 'm': /* Max hits */ + max_hits = -1; + if(*cur_arg && strchr("0123456789",(int) *cur_arg)) { + sscanf(cur_arg,"%d",&max_hits); + cur_arg += strspn(cur_arg,"0123456789"); + } + else if(argc > 1) { + tmp = sscanf(argv[1],"%d",&max_hits); + if (tmp == 1) {argc--;argv++;} + } + if (max_hits < 1) { + fprintf(stderr, "%s: -m option requires a value for max hits (>= 1)\n", + progname); + exit(A_EXIT); + } + break; + + case 'o': /* Offset */ + if(argc > 1) { + tmp = sscanf(argv[1],"%d",&offset); + if (tmp != 1) + argc = -1; + else { + argc--; argv++; + } + } + break; + + case 'r': /* Regular expression search */ + qtype = 'R'; + etype = 'r'; + break; + + case 's': /* substring (case insensitive) */ + qtype = 'S'; + etype = 's'; + break; + + case 't': /* Sort inverted by date */ + sortflag = 1; + break; + + case 'v': /* Display version */ + fprintf(stderr, + "Client version %s based upon Prospero version %s\n", + CLIENT_VERSION, PFS_RELEASE); + exitflag++; + break; + + default: + fprintf(stderr,"Usage: %s [-[cers][l][t][m#][h host][%s][%s#]%s string\n", progname, LFLAG, NFLAG, HFLAG); + exit(A_EXIT); + } + } + argc--; argv++; + } + + scandone: + + if (eflag) qtype = etype; + + if ((argc != 1) && exitflag) exit(0); + + if (argc != 1) { + fprintf(stderr, "Usage: %s [-[cers][l][t][m#][h host][%s][%s#]%s string\n", progname, LFLAG, NFLAG, HFLAG); + fprintf(stderr," -c : case sensitive substring search\n"); + fprintf(stderr," -e : exact string match (default)\n"); + fprintf(stderr," -r : regular expression search\n"); + fprintf(stderr," -s : case insensitive substring search\n"); + fprintf(stderr," -l : list one match per line\n"); + fprintf(stderr," -t : sort inverted by date\n"); + fprintf(stderr," -m# : specifies maximum number of hits to return (default %d)\n", max_hits); + fprintf(stderr," -h host : specifies server host\n"); + fprintf(stderr," -%s : list known servers and current default\n", LFLAG); + fprintf(stderr," -%s# : specifies query niceness level (0-35765)\n", NFLAG); + #ifdef CUTCP + fprintf(stderr,"-H config.tel: specify location of config.tel file\n"); + #endif + exit(A_EXIT); + } + + #ifdef CUTCP + if(argc = Snetinit()) { + fprintf(stderr,"Error %d from SNetinit (bad or missing config.tel ?)\n",argc); + if(argc == -2) + netshut(); /* rarp lookup failure */ + exit(1); + } + if(!hostset) { /* if no host on command line, look in config.tel file + for name=archie */ + struct machinfo *mp; + + mp = Shostlook("archie"); + if(mp) { + host = mp->hname ? mp->hname : mp->sname; + } + } + #endif + + procquery(host, argv[0], max_hits, offset, qtype, sortflag, listflag); + + #ifdef CUTCP + netshut(); + #endif + exit(0); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/archie.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/archie.h:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/archie.h Tue Oct 5 13:19:57 2004 *************** *** 0 **** --- 1,77 ---- + /* + * archie.h : Definitions for the programmatic Prospero interface to Archie + * + * Written by Brendan Kehoe (brendan at cs.widener.edu), + * George Ferguson (ferguson at cs.rochester.edu), and + * Clifford Neuman (bcn at isi.edu). + */ + + #ifdef VMS + /* + * This has to be edited if you're running VMS, cuz I gave up after about + * an hour trying to make DCL do /define(archie_host="\"FOO\"") + * + * Edit ARCHIE_HOST to be one of : + * archie.ans.net (USA [NY]) + * archie.rutgers.edu (USA [NJ]) + * archie.sura.net (USA [MD]) + * archie.mcgill.ca (Canada) + * archie.funet.fi (Finland/Mainland Europe) + * archie.au (Australia) + * archie.doc.ic.ac.uk (Great Britain/Ireland) + */ + #define ARCHIE_HOST "archie.ans.net" + #endif /* VMS */ + + /* You can't touch this. */ + #ifndef XARCHIE + # define ARCHIES "archie.ans.net (USA [NY])","archie.rutgers.edu (USA [NJ])","archie.sura.net (USA [MD])","archie.mcgill.ca (Canada)","archie.funet.fi (Finland/Mainland Europe)","archie.au (Australia)","archie.doc.ic.ac.uk (Great Britain/Ireland)" + # define NARCHIES 7 + #endif + + /* + * Default value for max hits. Note that this is normally different + * for different client implementations. Doing so makes it easier to + * collect statistics on the use of the various clients. + */ + #ifdef VMS + # define MAX_HITS 98 /* VMS Client */ + #else + # ifdef XARCHIE + # define MAX_HITS 99 /* X Client */ + # else + # define MAX_HITS 95 /* Normal client */ + # endif + #endif + + /* + * CLIENT_VERSION may be used to identify the version of the client if + * distributed separately from the Prospero distribution. The version + * command should then identify both the client version and the Prospero + * version identifiers. + */ + #ifdef XARCHIE + # define CLIENT_VERSION "1.3-X" + #else + # define CLIENT_VERSION "1.3" + #endif + + /* Procedures from user/aquery.c */ + + /* archie_query(host,string,max_hits,offset,query_type,cmp_proc,flags) */ + /* extern VLINK archie_query(); */ + + extern VLINK archie_query(char *host,char *string,int max_hits,int offset, + char query_type,int (*cmp_proc)(),int flags); + + /* defcmplink(p,q) and invdatecmplink(p,q) */ + extern int defcmplink(); /* Compare by host then by filename */ + extern int invdatecmplink(); /* Compare links inverted by date */ + + /* Definitions for the comparison procedures */ + #define AQ_DEFCMP defcmplink + #define AQ_INVDATECMP invdatecmplink + + /* Flags */ + #define AQ_NOSORT 0x01 /* Don't sort */ + #define AQ_NOTRANS 0x02 /* Don't translate Archie responses */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/atalloc.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/atalloc.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/atalloc.c Tue Oct 5 13:19:57 2004 *************** *** 0 **** --- 1,93 ---- + /* + * Copyright (c) 1989, 1990 by the University of Washington + * + * For copying and distribution information, please see the file + * . + */ + + #include + #include + #include + + #include + #include /* for correct definition of ZERO */ + + static PATTRIB lfree = NULL; + int pattrib_count = 0; + int pattrib_max = 0; + + extern void bzero(char *b,int length); + + /* + * atalloc - allocate and initialize vlink structure + * + * ATALLOC returns a pointer to an initialized structure of type + * PATTRIB. If it is unable to allocate such a structure, it + * returns NULL. + */ + + PATTRIB atalloc(void) + { + PATTRIB at; + if(lfree) { + at = lfree; + lfree = lfree->next; + } + else { + at = (PATTRIB) malloc(sizeof(PATTRIB_ST)); + if (!at) return(NULL); + pattrib_max++; + } + + pattrib_count++; + + ZERO(at); + /* Initialize and fill in default values; all items are + 0 [or NULL] save precedence */ + at->precedence = ATR_PREC_OBJECT; + + return(at); + } + + /* + * atfree - free a PATTRIB structure + * + * ATFREE takes a pointer to a PATTRRIB structure and adds it to + * the free list for later reuse. + */ + + void atfree(PATTRIB at) + { + if(at->aname) stfree(at->aname); + + if((strcmp(at->avtype,"ASCII") == 0) && at->value.ascii) + stfree(at->value.ascii); + if((strcmp(at->avtype,"LINK") == 0) && at->value.link) + vlfree(at->value.link); + + if(at->avtype) stfree(at->avtype); + + at->next = lfree; + at->previous = NULL; + lfree = at; + pattrib_count--; + } + + /* + * atlfree - free a PATTRIB structure + * + * ATLFREE takes a pointer to a PATTRIB structure frees it and any linked + * PATTRIB structures. It is used to free an entrie list of PATTRIB + * structures. + */ + + void atlfree(PATTRIB at) + { + PATTRIB nxt; + + while(at != NULL) { + nxt = at->next; + atfree(at); + at = nxt; + } + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/copyright.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/copyright.h:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/copyright.h Tue Oct 5 13:19:57 2004 *************** *** 0 **** --- 1,20 ---- + /* + Copyright (c) 1989, 1990, 1991 by the University of Washington + + Permission to use, copy, modify, and distribute this software and its + documentation for non-commercial purposes and without fee is hereby + granted, provided that the above copyright notice appear in all copies + and that both the copyright notice and this permission notice appear in + supporting documentation, and that the name of the University of + Washington not be used in advertising or publicity pertaining to + distribution of the software without specific, written prior + permission. The University of Washington makes no representations + about the suitability of this software for any purpose. It is + provided "as is" without express or implied warranty. + + Prospero was written by Clifford Neuman (bcn at isi.edu). + + Questions concerning this software should be directed to + info-prospero at isi.edu. + + */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/dirsend.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/dirsend.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/dirsend.c Tue Oct 5 13:19:57 2004 *************** *** 0 **** --- 1,1093 ---- + /* + * Copyright (c) 1989, 1990, 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + * + * v1.2.8 - 12/17/91 (jwb) - fixed warning message + * v1.2.7 - 12/13/91 (bpk) - took out XARCHIE code since we've diverged + * v1.2.6 - 12/13/91 (jwb) - UCX stuff + * v1.2.5 - 11/21/91 (bkc) - new version for CUTCP, ugly as it is. + * v1.2.4 - 11/19/91 (mmt) - added MSDOS & OS2 stuff + * v1.2.3 - 11/04/91 (bcn) - removed host comparison and replaced with check + * for connection id (undoes effect of v1.2.2.). + * v1.2.2 - 11/02/91 (gf) - removed extra inet_ntoa() calls and stuff for + * multi-interface nets (lmjm at doc.imperial.ac.uk) + * v1.2.1 - 10/20/91 (gf) - asynch implementation + * v1.2.0 - 09/17/91 (bpk) - added BULL & USG stuff, thanks to Jim Sillas + * v1.1.2 - 08/30/91 (bpk) - added VMS support + * v1.1.1 - 08/29/91 (bcn) - changed backoff handling + * v1.1.0 - 08/13/91 (gf) - added XArchie status calls + * + * gf: 20 Oct 1991: + * Broken into pieces so that under X dirsend() doesn't block in select() + * but rather uses Xt calls to allow continued event processing. If + * XARCHIE is not defined, can still be used since processEvent() will + * use select() in this case. + */ + + /* If you're going to hack on this, I'd suggest using unifdef with -UCUTCP + and possibly -UVMS, for your working copy. When you've got your changes + done, come back and add them into this main file. It's getting pretty + nasty down there. */ + + #include + #include + #include + #include + #include + + #ifdef VMS + # ifdef WOLLONGONG + # include "twg$tcp:[netdist.include]netdb.h" + # else /* not Wollongong */ + # ifdef UCX + # include netdb + # else /* Multinet */ + # include "multinet_root:[multinet.include]netdb.h" + # endif + # endif + # include + #else /* not VMS */ + # include /* this may/will define FD_SET etc */ + # ifdef u3b2 + # include /* THIS does FD_SET etc on AT&T 3b2s. */ + # endif /* u3b2 */ + # include + # if defined(NEED_TIME_H) && !defined(AUX) + # include + # else + # include + # endif + # ifdef NEED_STRING_H + # include + # else + # include + # endif + # ifdef CUTCP + # include + # include + # include + # else /* not CUTCP */ + # include + # include + # endif + # ifdef NEED_SELECT_H + # include + # endif /* NEED_SELECT_H */ + # ifndef IN_H + # include + # define IN_H + # endif + # ifndef hpux + # include + # endif + #endif /* !VMS */ + + /* Interactive UNIX keeps some of the socket definitions in funny places. */ + #ifdef ISC + # include + #endif /* ISC */ + + #include + #include + #include + #include + + /* Gnu C currently fails to pass structures on Sparcs properly. This directly + effects the calling of inet_ntoa(). To get around it, we use this hack; + take the address of what's being called to inet_ntoa, so it gets it + properly. This won't be necessary with gcc 2.0. */ + #if defined(sun) && defined(__GNUC__) && !defined(__GNU_LIBRARY__) + # define SUN_GNU_FIX & + #else + # define SUN_GNU_FIX + #endif + + static int notprived = 0; + #ifndef MSDOS + extern int errno; + #endif + extern int perrno; + extern int rdgram_priority; + #ifdef DEBUG + extern int pfs_debug; + #endif + extern int pfs_disable_flag; + + char *nlsindex(); + + #define max(X, Y) ((X) > (Y) ? (X) : (Y)) + + static int dir_udp_port = 0; /* Remote UDP port number */ + + #ifdef CUTCP + # define NS_TIMEOUT 15 + #endif + + static unsigned short next_conn_id = 0; + + static int client_dirsrv_timeout = CLIENT_DIRSRV_TIMEOUT; + static int client_dirsrv_retry = CLIENT_DIRSRV_RETRY; + + /* These were parameters to dirsend() */ + static PTEXT pkt; + static char *hostname; + static struct sockaddr_in *hostaddr; + + /* These were locals in dirsend(). Note that the initializations here + * are really meaningless since we have to redo them for each call to + * dirsend() since they were formerly automatically initialized. + */ + static PTEXT first = NULL; /* First returned packet */ + static PTEXT next; /* The one we are waiting for */ + static PTEXT vtmp; /* For reorganizing linked list */ + static PTEXT comp_thru; /* We have all packets though */ + static int lp = -1; /* Opened UDP port */ + static int hdr_len; /* Header Length */ + static int nd_pkts; /* Number of packets we want */ + static int no_pkts; /* Number of packets we have */ + static int pkt_cid; /* Packet connection identifier */ + static unsigned short this_conn_id; /* Connection ID we are using */ + static unsigned short recvd_thru; /* Received through */ + static short priority; /* Priority for request */ + static short one = 0; /* Pointer to value 1 */ + static short zero = 0; /* Pointer to value 0 */ + static char *seqtxt; /* Pointer to text w/ sequence # */ + static struct sockaddr_in us; /* Our address */ + static struct sockaddr_in to; /* Address to send query */ + static struct sockaddr_in from; /* Reply received from */ + static int from_sz; /* Size of from structure */ + static struct hostent *host; /* Host info from gethostbyname */ + static long newhostaddr; /* New host address from *host */ + static int req_udp_port=0; /* Requested port (optional) */ + static char *openparen; /* Delimits port in name */ + static char hostnoport[500];/* Host name without port */ + static int ns; /* Number of bytes actually sent */ + static int nr; /* Number of bytes received */ + static SELECTARG readfds; /* Used for select */ + static int tmp; + static char *ctlptr; /* Pointer to control field */ + static short stmp; /* Temp short for conversions */ + static int backoff; /* Server requested backoff */ + static unsigned char rdflag11; /* First byte of flags (bit vect)*/ + static unsigned char rdflag12; /* Second byte of flags (int) */ + static int scpflag = 0; /* Set if any sequencd cont pkts */ + static int ackpend = 0; /* Acknowledgement pending */ + static int gaps = 0; /* Gaps present in recvd pkts */ + static struct timeval timeout; /* Time to wait for response */ + static struct timeval ackwait; /* Time to wait before acking */ + static struct timeval gapwait; /* Time to wait b4 filling gaps */ + static struct timeval *selwait; /* Time to wait for select */ + static int retries; /* was = client_dirsrv_retry */ + char to_hostname[512]; /* lmjm: saves inet_ntoa() str */ + + /* These are added so dirsend() "blocks" properly */ + static PTEXT dirsendReturn; + static int dirsendDone; + + /* And here are the values for dirsendDone */ + #define DSRET_DONE 1 + #define DSRET_SEND_ERROR -1 + #define DSRET_RECV_ERROR -2 + #define DSRET_SELECT_ERROR -3 + #define DSRET_TIMEOUT -4 + #define DSRET_ABORTED -5 + + /* New procedures to break up dirsend() */ + static int initDirsend(); + static void retryDirsend(), keepWaitingDirsend(); + static void timeoutProc(); + static void readProc(); + + /* Wrappers around X calls to allow non-X usage */ + static void processEvent(); + + /* Extra stuff for the asynchronous X version of dirsend() */ + typedef char *XtPointer; + typedef char *XtInputId; + typedef char *XtIntervalId; + + static XtInputId inputId; + static XtIntervalId timerId = (XtIntervalId)0; + + /* + * dirsend - send packet and receive response + * + * DIRSEND takes a pointer to a structure of type PTEXT, a hostname, + * and a pointer to a host address. It then sends the supplied + * packet off to the directory server on the specified host. If + * hostaddr points to a valid address, that address is used. Otherwise, + * the hostname is looked up to obtain the address. If hostaddr is a + * non-null pointer to a 0 address, then the address will be replaced + * with that found in the hostname lookup. + * + * DIRSEND will wait for a response and retry an appropriate + * number of times as defined by timeout and retries (both static + * variables). It will collect however many packets form the reply, and + * return them in a structure (or structures) of type PTEXT. + * + * DIRSEND will free the packet that it is presented as an argument. + * The packet is freed even if dirsend fails. + */ + + PTEXT dirsend(PTEXT pkt_p,char *hostname_p,struct sockaddr_in *hostaddr_p) + { + /* copy parameters to globals since other routines use them */ + pkt = pkt_p; + hostname = hostname_p; + hostaddr = hostaddr_p; + /* Do the initializations of formerly auto variables */ + first = NULL; + lp = -1; + one = 0; + zero = 0; + req_udp_port=0; + scpflag = 0; + ackpend = 0; + gaps = 0; + retries = client_dirsrv_retry; + + if (initDirsend() < 0) + return(NULL); + + /* set the first timeout */ + retryDirsend(); + + dirsendReturn = NULL; + dirsendDone = 0; + /* Until one of the callbacks says to return, keep processing events */ + while (!dirsendDone) + processEvent(); + + /* Return whatever we're supposed to */ + return(dirsendReturn); + } + + + /* - - - - - - - - */ + /* This function does all the initialization that used to be done at the + * start of dirsend(), including opening the socket descriptor "lp". It + * returns the descriptor if successful, otherwise -1 to indicate that + * dirsend() should return NULL immediately. + */ + + static int initDirsend(void) + { + if(one == 0) one = htons((short) 1); + + priority = htons(rdgram_priority); + + timeout.tv_sec = client_dirsrv_timeout; + timeout.tv_usec = 0; + + ackwait.tv_sec = 0; + ackwait.tv_usec = 500000; + + gapwait.tv_sec = (client_dirsrv_timeout < 5 ? client_dirsrv_timeout : 5); + gapwait.tv_usec = 0; + + comp_thru = NULL; + perrno = 0; + nd_pkts = 0; + no_pkts = 0; + pkt_cid = 0; + + /* Find first connection ID */ + if(next_conn_id == 0) { + srand(getpid()+time(0)); /* XXX: arg ok, but not right type. */ + next_conn_id = rand(); + } + + + /* If necessary, find out what udp port to send to */ + if (dir_udp_port == 0) { + register struct servent *sp; + tmp = pfs_enable; pfs_enable = PMAP_DISABLE; + #ifdef USE_ASSIGNED_PORT + /* UCX needs 0 & -1 */ + if ((sp = getservbyname("prospero","udp")) <= 0) { + #ifdef DEBUG + if (pfs_debug) + fprintf(stderr, "dirsrv: udp/prospero unknown service - using %d\n", + PROSPERO_PORT); + #endif + dir_udp_port = htons((u_short) PROSPERO_PORT); + } + #else + /* UCX needs 0 & -1 */ + sp = getservbyname("dirsrv","udp"); + if (sp == (struct servent *)0 || sp == (struct servent *)-1) { + #ifdef DEBUG + if (pfs_debug) + fprintf(stderr, "dirsrv: udp/dirsrv unknown service - using %d\n", + DIRSRV_PORT); + #endif + dir_udp_port = htons((unsigned short) DIRSRV_PORT); + } + #endif + else dir_udp_port = sp->s_port; + pfs_enable = tmp; + #ifdef DEBUG + if (pfs_debug > 3) + fprintf(stderr,"dir_udp_port is %d\n", ntohs(dir_udp_port)); + #endif + } + + /* If we were given the host address, then use it. Otherwise */ + /* lookup the hostname. If we were passed a host address of */ + /* 0, we must lookup the host name, then replace the old value */ + if(!hostaddr || (hostaddr->sin_addr.s_addr == 0)) { + /* I we have a null host name, return an error */ + if((hostname == NULL) || (*hostname == '\0')) { + #ifdef DEBUG + if (pfs_debug) + fprintf(stderr, "dirsrv: Null hostname specified\n"); + #endif + perrno = DIRSEND_BAD_HOSTNAME; + ptlfree(pkt); + /* return(NULL); */ + return(-1); + } + /* If a port is included, save it away */ + if((openparen = strchr(hostname,(int) '('))) { + sscanf(openparen+1,"%d",&req_udp_port); + strncpy(hostnoport,hostname,400); + if((openparen - hostname) < 400) { + *(hostnoport + (openparen - hostname)) = '\0'; + hostname = hostnoport; + } + } + tmp = pfs_enable; pfs_enable = PMAP_DISABLE; + if((host = gethostbyname(hostname)) == NULL) { + pfs_enable = tmp; + /* Check if a numeric address */ + newhostaddr = inet_addr(hostname); + if(newhostaddr == -1) { + #ifdef DEBUG + if (pfs_debug) + fprintf(stderr, "dirsrv: Can't resolve host %s\n",hostname); + #endif + perrno = DIRSEND_BAD_HOSTNAME; + ptlfree(pkt); + /* return(NULL); */ + return(-1); + } + bzero((char *)&to, S_AD_SZ); + to.sin_family = AF_INET; + bcopy(&newhostaddr,&to.sin_addr, 4); + if(hostaddr) bcopy(&to,hostaddr, S_AD_SZ); + } + else { + pfs_enable = tmp; + bzero((char *)&to, S_AD_SZ); + to.sin_family = host->h_addrtype; + #ifdef CUTCP + bcopy(&host->h_addr, &to.sin_addr, host->h_length); + #else + bcopy(host->h_addr, &to.sin_addr, host->h_length); + #endif + if(hostaddr) bcopy(&to, hostaddr, S_AD_SZ); + } + } + else bcopy(hostaddr, &to, S_AD_SZ); + /* lmjm: Save away the hostname */ + strncpy(to_hostname, + inet_ntoa(/* SUN_GNU_FIX */ to.sin_addr), + sizeof(to_hostname)-1); + + if(req_udp_port) to.sin_port = htons(req_udp_port); + else to.sin_port = dir_udp_port; + + /* If a port was specified in hostaddr, use it, otherwise fill it in */ + if(hostaddr) { + if(hostaddr->sin_port) to.sin_port = hostaddr->sin_port; + else hostaddr->sin_port = to.sin_port; + } + + #ifndef CUTCP + /* Must open a new port each time. we do not want to see old */ + /* responses to messages we are done with */ + if ((lp = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { + #ifdef DEBUG + if (pfs_debug) + fprintf(stderr,"dirsrv: Can't open socket\n"); + #endif + perrno = DIRSEND_UDP_CANT; + ptlfree(pkt); + /* return(NULL); */ + return(-1); + } + #endif /* not CUTCP */ + + /* Try to bind it to a privileged port - loop through candidate */ + /* ports trying to bind. If failed, that's OK, we will let the */ + /* system assign a non-privileged port later */ + #ifndef CUTCP + if(!notprived) { + for(tmp = PROS_FIRST_PRIVP; tmp < PROS_FIRST_PRIVP+PROS_NUM_PRIVP; + tmp++) { + #endif + bzero((char *)&us, sizeof(us)); + us.sin_family = AF_INET; + #ifndef CUTCP + us.sin_port = htons((unsigned short) tmp); + if (bind(lp, (struct sockaddr *)&us, sizeof(us))) { + if(errno != EADDRINUSE) { + notprived++; + break; + } + } + else break; + } + } + #else + us.sin_port = htons(PROS_FIRST_PRIVP); + netulisten(PROS_FIRST_PRIVP); + #endif + + #ifndef USE_V3_PROT + /* Add header */ + if(rdgram_priority) { + pkt->start -= 15; + pkt->length += 15; + *(pkt->start) = (char) 15; + bzero(pkt->start+9,4); + *(pkt->start+11) = 0x02; + bcopy(&priority,pkt->start+13,2); + } + else { + pkt->start -= 9; + pkt->length += 9; + *(pkt->start) = (char) 9; + } + this_conn_id = htons(next_conn_id++); + if(next_conn_id == 0) next_conn_id++; + bcopy(&this_conn_id,pkt->start+1,2); + bcopy(&one,pkt->start+3,2); + bcopy(&one,pkt->start+5,2); + bzero(pkt->start+7,2); + #endif + + #ifdef DEBUG + if (pfs_debug > 2) { + #ifndef USE_V3_PROT + if (to.sin_family == AF_INET) { + if(req_udp_port) + fprintf(stderr,"Sending message to %s+%d(%d)...", + to_hostname, req_udp_port, ntohs(this_conn_id)); + else fprintf(stderr,"Sending message to %s(%d)...", + to_hostname, ntohs(this_conn_id)); + } + #else + if (to.sin_family == AF_INET) + fprintf(stderr,"Sending message to %s...", to_hostname); + #endif /* USE_V3_PROT */ + else + fprintf(stderr,"Sending message..."); + (void) fflush(stderr); + } + #endif /* DEBUG */ + + first = ptalloc(); + next = first; + + #ifndef CUTCP + return(lp); + #else + return(1); + #endif /* CUTCP */ + } + + /* - - - - - - - - */ + /* + * This used to be a label to goto to retry the last packet. Now we resend + * the packet and call keepWaitingDirsend() to wait for a reply. (We + * call keepWaitingDirsend() because formerly the code dropped through + * the keep_waiting label.) + */ + + static void retryDirsend(void) + { + #ifdef CUTCP + int lretry = 3; + #endif + gaps = ackpend = 0; + + #ifndef CUTCP + ns = sendto(lp,(char *)(pkt->start), pkt->length, 0, (struct sockaddr *)&to, S_AD_SZ); + #else + while(--lretry) { + ns = netusend(&to.sin_addr,ntohs(to.sin_port),ntohs(us.sin_port), + (char *) pkt->start, pkt->length); + if(!ns) + break; + Stask(); + Stask(); + Stask(); + } + #endif /* CUTCP */ + + #ifndef CUTCP + if(ns != pkt->length) { + #else + if(ns != 0) { + #endif + #ifdef DEBUG + if (pfs_debug) { + fprintf(stderr,"\nsent only %d/%d: ",ns, pkt->length); + perror(""); + } + #endif + close(lp); + perrno = DIRSEND_NOT_ALL_SENT; + ptlfree(first); + ptlfree(pkt); + /* return(NULL); */ + dirsendReturn = NULL; + dirsendDone = DSRET_SEND_ERROR; + } + #ifdef DEBUG + if (pfs_debug > 2) fprintf(stderr,"Sent.\n"); + #endif + keepWaitingDirsend(); + } + + /* - - - - - - - - */ + /* + * This used to be a label to goto to set the appropriate timeout value + * and blocked in select(). Now we set selwait and the SELECTARGs to the + * appropriate values, and in X register a new timeout, then return to + * allow event processing. + */ + + static void keepWaitingDirsend(void) + { + /* We come back to this point (by a goto) if the packet */ + /* received is only part of the response, or if the */ + /* response came from the wrong host */ + + #ifdef DEBUG + if (pfs_debug > 2) fprintf(stderr,"Waiting for reply..."); + #endif + + #ifndef CUTCP + FD_ZERO(&readfds); + FD_SET(lp, &readfds); + #endif + + if(ackpend) selwait = &ackwait; + else if(gaps) selwait = &gapwait; + else selwait = &timeout; + } + + /* - - - - - - - - */ + /* + * This routine is called when a timeout occurs. It includes the code that + * was formerly used when select() returned 0 (indicating a timeout). + */ + /*ARGSUSED*/ + + static void timeoutProc(XtPointer client_data,XtIntervalId *id) + { + if (gaps || ackpend) { /* Send acknowledgment */ + /* Acks are piggybacked on retries - If we have received */ + /* an ack from the server, then the packet sent is only */ + /* an ack and the rest of the message will be empty */ + #ifdef DEBUG + if (pfs_debug > 2) { + fprintf(stderr,"Acknowledging (%s).\n", + (ackpend ? "requested" : "gaps")); + } + #endif + retryDirsend(); + return; + } + + if (retries-- > 0) { + timeout.tv_sec = CLIENT_DIRSRV_BACKOFF(timeout.tv_sec); + #ifdef DEBUG + if (pfs_debug > 2) { + fprintf(stderr,"Timed out. Setting timeout to %d seconds.\n", + (int) timeout.tv_sec); + } + #endif + retryDirsend(); + return; + } + + #ifdef DEBUG + if (pfs_debug) { + fprintf(stderr, "select failed(timeoutProc): readfds=%x ", + readfds); + perror(""); + } + #endif + #ifndef CUTCP + close(lp); + #endif + perrno = DIRSEND_SELECT_FAILED; + ptlfree(first); + ptlfree(pkt); + /* return(NULL); */ + dirsendReturn = NULL; + dirsendDone = DSRET_TIMEOUT; + } + + /* - - - - - - - - */ + /* + * This function is called whenever there's something to read on the + * connection. It includes the code that was run when select() returned + * greater than 0 (indicating read ready). + */ + /*ARGSUSED*/ + + static void readProc(XtPointer client_data,int *source,XtInputId *id) + { + #ifdef CUTCP + int lretry = 3; + #endif + + from_sz = sizeof(from); + next->start = next->dat; + + #ifndef CUTCP + if ((nr = recvfrom(lp, next->start, sizeof(next->dat), 0, (struct sockaddr *)&from, &from_sz)) < 0) { + #else + nr = neturead(next->start); + if (nr < 1) { + #endif + #ifdef DEBUG + if (pfs_debug) perror("recvfrom"); + #endif + #ifndef CUTCP + close(lp); + #endif + perrno = DIRSEND_BAD_RECV; + ptlfree(first); + ptlfree(pkt); + /* return(NULL) */ + dirsendReturn = NULL; + dirsendDone = DSRET_RECV_ERROR; + return; + } + + next->length = nr; + next->start[next->length] = 0; + + #ifdef DEBUG + if (pfs_debug > 2) + fprintf(stderr,"Received packet from %s\n", + /* + inet_ntoa(SUN_GNU_FIX *(struct in_addr *)&from.sin_addr)); + */ + inet_ntoa(from.sin_addr)); + #endif + + + /* For the current format, if the first byte is less than */ + /* 20, then the first two bits are a version number and the next six */ + /* are the header length (including the first byte). */ + if((hdr_len = (unsigned char) *(next->start)) < 20) { + ctlptr = next->start + 1; + next->seq = 0; + if(hdr_len >= 3) { /* Connection ID */ + bcopy(ctlptr,(char *) &stmp,2); + if(stmp) pkt_cid = ntohs(stmp); + ctlptr += 2; + } + if(pkt_cid && this_conn_id && (pkt_cid != this_conn_id)) { + /* The packet is not for us */ + /* goto keep_waiting; */ + keepWaitingDirsend(); + return; + } + if(hdr_len >= 5) { /* Packet number */ + bcopy(ctlptr,&stmp,2); + next->seq = ntohs(stmp); + ctlptr += 2; + } + else { /* No packet number specified, so this is the only one */ + next->seq = 1; + nd_pkts = 1; + } + if(hdr_len >= 7) { /* Total number of packets */ + bcopy(ctlptr,&stmp,2); /* 0 means don't know */ + if(stmp) nd_pkts = ntohs(stmp); + ctlptr += 2; + } + if(hdr_len >= 9) { /* Receievd through */ + bcopy(ctlptr,&stmp,2); /* 1 means received request */ + #ifndef USE_V3_PROT + if((stmp) && (ntohs(stmp) == 1)) { + /* Future retries will be acks only */ + pkt->length = 9; + bcopy(&zero,pkt->start+3,2); + #ifdef DEBUG + if(pfs_debug > 2) + fprintf(stderr,"Server acked request - retries will be acks only\n"); + #endif + } + #endif + ctlptr += 2; + } + if(hdr_len >= 11) { /* Backoff */ + bcopy(ctlptr,&stmp,2); + if(stmp) { + backoff = ntohs(stmp); + #ifdef DEBUG + if(pfs_debug > 2) + fprintf(stderr,"Backing off to %d seconds\n", backoff); + #endif + timeout.tv_sec = backoff; + if ((backoff > 60) && (first == next) && (no_pkts == 0)) { + /* Probably a long queue on the server - don't give up */ + retries = client_dirsrv_retry; + } + } + ctlptr += 2; + } + if(hdr_len >= 12) { /* Flags (1st byte) */ + bcopy(ctlptr,&rdflag11,1); + if(rdflag11 & 0x80) { + #ifdef DEBUG + if(pfs_debug > 2) + fprintf(stderr,"Ack requested\n"); + #endif + ackpend++; + } + if(rdflag11 & 0x40) { + #ifdef DEBUG + if(pfs_debug > 2) + fprintf(stderr,"Sequenced control packet\n"); + #endif + next->length = -1; + scpflag++; + } + ctlptr += 1; + } + if(hdr_len >= 13) { /* Flags (2nd byte) */ + /* Reserved for future use */ + bcopy(ctlptr,&rdflag12,1); + ctlptr += 1; + } + if(next->seq == 0) { + /* goto keep_waiting; */ + keepWaitingDirsend(); + return; + } + if(next->length >= 0) next->length -= hdr_len; + next->start += hdr_len; + goto done_old; + } + + pkt_cid = 0; + + /* if intermediate format (between old and new), then process */ + /* and go to done_old */ + ctlptr = next->start + max(0,next->length-20); + while(*ctlptr) ctlptr++; + /* Control fields start after the terminating null */ + ctlptr++; + /* Until old version are gone, must be 4 extra bytes minimum */ + /* When no version 3 servers, can remove the -4 */ + if(ctlptr < (next->start + next->length - 4)) { + /* Connection ID */ + bcopy(ctlptr,&stmp,2); + if(stmp) pkt_cid = ntohs(stmp); + ctlptr += 2; + if(pkt_cid && this_conn_id && (pkt_cid != this_conn_id)) { + /* The packet is not for us */ + /* goto keep_waiting; */ + keepWaitingDirsend(); + return; + } + /* Packet number */ + if(ctlptr < (next->start + next->length)) { + bcopy(ctlptr,&stmp,2); + next->seq = ntohs(stmp); + ctlptr += 2; + } + /* Total number of packets */ + if(ctlptr < (next->start + next->length)) { + bcopy(ctlptr,&stmp,2); + if(stmp) nd_pkts = ntohs(stmp); + ctlptr += 2; + } + /* Receievd through */ + if(ctlptr < (next->start + next->length)) { + /* Not supported by clients */ + ctlptr += 2; + } + /* Backoff */ + if(ctlptr < (next->start + next->length)) { + bcopy(ctlptr,&stmp,2); + backoff = ntohs(stmp); + #ifdef DEBUG + if(pfs_debug > 2) + fprintf(stderr,"Backing off to %d seconds\n", backoff); + #endif + if(backoff) timeout.tv_sec = backoff; + ctlptr += 2; + } + if(next->seq == 0) { + /* goto keep_waiting; */ + keepWaitingDirsend(); + return; + } + goto done_old; + + } + + /* Notes that we have to start searching 11 bytes before the */ + /* expected start of the MULTI-PACKET line because the message */ + /* might include up to 10 bytes of data after the trailing null */ + /* The order of those bytes is two bytes each for Connection ID */ + /* Packet-no, of, Received-through, Backoff */ + seqtxt = nlsindex(next->start + max(0,next->length - 40),"MULTI-PACKET"); + if(seqtxt) seqtxt+= 13; + + if((nd_pkts == 0) && (no_pkts == 0) && (seqtxt == NULL)) goto all_done; + + tmp = sscanf(seqtxt,"%d OF %d", &(next->seq), &nd_pkts); + #ifdef DEBUG + if (pfs_debug && (tmp == 0)) + fprintf(stderr,"Cant read packet sequence number: %s", seqtxt); + #endif + done_old: + #ifdef DEBUG + if(pfs_debug > 2) fprintf(stderr,"Packet %d of %d\n",next->seq,nd_pkts); + #endif + if ((first == next) && (no_pkts == 0)) { + if(first->seq == 1) { + comp_thru = first; + /* If only one packet, then return it */ + if(nd_pkts == 1) goto all_done; + } + else gaps++; + no_pkts = 1; + next = ptalloc(); + /* goto keep_waiting; */ + keepWaitingDirsend(); + return; + } + + if(comp_thru && (next->seq <= comp_thru->seq)) + ptfree(next); + else if (next->seq < first->seq) { + vtmp = first; + first = next; + first->next = vtmp; + first->previous = NULL; + vtmp->previous = first; + if(first->seq == 1) comp_thru = first; + no_pkts++; + } + else { + vtmp = (comp_thru ? comp_thru : first); + while (vtmp->seq < next->seq) { + if(vtmp->next == NULL) { + vtmp->next = next; + next->previous = vtmp; + next->next = NULL; + no_pkts++; + goto ins_done; + } + vtmp = vtmp->next; + } + if(vtmp->seq == next->seq) + ptfree(next); + else { + vtmp->previous->next = next; + next->previous = vtmp->previous; + next->next = vtmp; + vtmp->previous = next; + no_pkts++; + } + } + + ins_done: + + while(comp_thru && comp_thru->next && + (comp_thru->next->seq == (comp_thru->seq + 1))) { + comp_thru = comp_thru->next; + #ifndef USE_V3_PROT + recvd_thru = htons(comp_thru->seq); + bcopy(&recvd_thru,pkt->start+7,2); /* Let server know we got it */ + #endif + /* We've made progress, so reset retry count */ + retries = client_dirsrv_retry; + /* Also, next retry will be only an acknowledgement */ + /* but for now, we can't fill in the ack field */ + #ifdef DEBUG + if(pfs_debug > 2) + fprintf(stderr,"Packets now received through %d\n",comp_thru->seq); + #endif + } + + /* See if there are any gaps */ + if(!comp_thru || comp_thru->next) gaps++; + else gaps = 0; + + if ((nd_pkts == 0) || (no_pkts < nd_pkts)) { + next = ptalloc(); + /* goto keep_waiting; */ + keepWaitingDirsend(); + return; + } + + all_done: + if(ackpend) { /* Send acknowledgement if requested */ + #ifdef DEBUG + if (pfs_debug > 2) { + if (to.sin_family == AF_INET) + fprintf(stderr,"Acknowledging final packet to %s(%d)\n", + to_hostname, ntohs(this_conn_id)); + else + fprintf(stderr,"Acknowledging final packet\n"); + (void) fflush(stderr); + } + #endif + #ifndef CUTCP + ns = sendto(lp,(char *)(pkt->start), pkt->length, 0, (struct sockaddr *)&to, S_AD_SZ); + #else + while(--lretry) { + ns = netusend(&to.sin_addr, ntohs(to.sin_port), ntohs(us.sin_port),(char *) pkt->start, pkt->length); + if(!ns) + break; + Stask(); + Stask(); + } + #endif + + #ifndef CUTCP + if(ns != pkt->length) { + #else + if(ns != 0) { + #endif + + #ifdef DEBUG + if (pfs_debug) { + fprintf(stderr,"\nsent only %d/%d: ",ns, pkt->length); + perror(""); + } + #endif + } + + } + #ifndef CUTCP + close(lp); + #endif + ptlfree(pkt); + + /* Get rid of any sequenced control packets */ + if(scpflag) { + while(first && (first->length < 0)) { + vtmp = first; + first = first->next; + if(first) first->previous = NULL; + ptfree(vtmp); + } + vtmp = first; + while(vtmp && vtmp->next) { + if(vtmp->next->length < 0) { + if(vtmp->next->next) { + vtmp->next = vtmp->next->next; + ptfree(vtmp->next->previous); + vtmp->next->previous = vtmp; + } + else { + ptfree(vtmp->next); + vtmp->next = NULL; + } + } + vtmp = vtmp->next; + } + } + + /* return(first); */ + dirsendReturn = first; + dirsendDone = DSRET_DONE; + + } + + static void processEvent(void) + { + #ifdef CUTCP + unsigned long now; + #endif + /* select - either recv is ready, or timeout */ + /* see if timeout or error or wrong descriptor */ + #ifndef CUTCP + tmp = select(lp + 1, &readfds, (SELECTARG *)0, (SELECTARG *)0, selwait); + if (tmp == 0) { + timeoutProc(NULL,&timerId); + } else if ((tmp < 0) || !FD_ISSET(lp,&readfds)) { + #ifdef DEBUG + if (pfs_debug) { + fprintf(stderr, "select failed(processEvent): readfds=%x ", + readfds); + perror(""); + } + #endif + close(lp); + #else /* CUTCP's flood. */ + /* while not timeout in selwait loop, stask looking for uevents */ + now = time(NULL) + selwait->tv_sec; + #ifdef DEBUG + if(pfs_debug) { + fprintf(stderr,"Waiting %d seconds\n",selwait->tv_sec); + } + + #endif + while(now > time(NULL)) { + int i, cl, dat; + + Stask(); + if (0 < (i = Sgetevent(USERCLASS, &cl, &dat))) { + /* got a user class event */ + if(cl == USERCLASS && + i == UDPDATA) { + readProc(NULL,&lp,&inputId); + return; + } + } + if(kbhit()) { + int c = getch(); + if(c == 27 || c == 3) + break; + fprintf(stderr,"Press to abort\n"); + } + } + if(now <= time(NULL)) { /* timeout */ + timeoutProc(NULL,&timerId); + return; + } + + #endif /* CUTCP */ + perrno = DIRSEND_SELECT_FAILED; + ptlfree(first); + ptlfree(pkt); + /* return(NULL); */ + dirsendReturn = NULL; + dirsendDone = DSRET_SELECT_ERROR; + #ifndef CUTCP + } else { + readProc(NULL,&lp,&inputId); + } + #endif /* CUTCP */ + } + + void abortDirsend(void) + { + if (!dirsendDone) { + #ifndef CUTCP + close(lp); + #endif + ptlfree(first); + ptlfree(pkt); + dirsendReturn = NULL; + dirsendDone = DSRET_ABORTED; + } + return; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/get_pauth.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/get_pauth.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/get_pauth.c Tue Oct 5 13:19:57 2004 *************** *** 0 **** --- 1,93 ---- + /* + * Copyright (c) 1989, 1990 by the University of Washington + * + * For copying and distribution information, please see the file + * . + * + * v1.2.2 - 11/19/91 (mmt) - added MSDOS & OS2 stuff + * v1.2.1 - 09/17/91 (bpk) - added BULL & USG stuff, thanks to Jim Sillas + * v1.2.0 - 09/17/91 (bpk) - fixed it up (thanks to synful) + * v1.1.1 - 08/30/91 (bpk) - added VMS support + */ + + #include + #include + #include + #ifndef VMS + # include /* this may/will define FD_SET etc */ + # include + #endif + + #ifdef NEED_STRING_H + # include + #else + # include + #endif + + #ifndef VMS + # if defined(MSDOS) && !defined(OS2) + # ifndef CUTCP + # include + # endif + # else + # include + # endif + #else + # include + # include + #endif + + #include + #include + + PAUTH get_pauth(int type) + { + static PAUTH_ST no_auth_st; + static PAUTH no_auth = NULL; + #if !defined(VMS) && !defined(MSDOS) || defined(OS2) + struct passwd *whoiampw; + #else + char username[13]; + unsigned short usernamelen; + struct { + unsigned short buflen; + unsigned short itmcod; + char *bufadr; + unsigned short *retlenadr; + unsigned long null; + } jpi_itemlist; + #endif + + if(no_auth == NULL) { + no_auth = &no_auth_st; + strcpy(no_auth->auth_type,"UNAUTHENTICATED"); + + /* find out who we are */ + #ifndef VMS + #if defined(MSDOS) && !defined(OS2) + #ifndef CUTCP + if (!getconf("general", "user", no_auth->authenticator, 250) + || (strlen (no_auth->authenticator) == 0)) + #endif + strcpy(no_auth->authenticator,"nobody"); + #else /* not MSDOS */ + DISABLE_PFS(whoiampw = getpwuid(getuid())); + if (whoiampw == 0) strcpy(no_auth->authenticator,"nobody"); + else strcpy(no_auth->authenticator, whoiampw->pw_name); + #endif /* not MSDOS */ + #else + jpi_itemlist.buflen = sizeof(username); + jpi_itemlist.itmcod = JPI$_USERNAME; + jpi_itemlist.bufadr = &username; + jpi_itemlist.retlenadr = &usernamelen; + jpi_itemlist.null = 0; + if (SYS$GETJPI(0, 0, 0, &jpi_itemlist, 0, 0, 0) & 0x1) + { + username[usernamelen] = 0; + strcpy(no_auth->authenticator, username); + } else + strcpy(no_auth->authenticator, "nobody"); + #endif + } + return(no_auth); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/get_vdir.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/get_vdir.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/get_vdir.c Tue Oct 5 13:19:57 2004 *************** *** 0 **** --- 1,487 ---- + /* + * Copyright (c) 1989, 1990, 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + * + * v1.2.2 - 11/19/91 (mmt) - added MSDOS & OS2 stuff + * v1.2.1 - 10/23/91 (bpk) - added missing code + * v1.2.0 - 09/17/91 (bpk) - added new get_vdir code + * v1.1.1 - 08/30/91 (bpk) - cast rindex() + */ + + #include + #include + + #include + #include + #include + #include + #include + #include + + #ifdef NEED_STRING_H + # include + #else + # include + #endif + + #ifdef DEBUG + extern int pfs_debug; + #endif + + extern int pwarn; + extern char p_warn_string[]; + extern int perrno; + extern char p_err_string[]; + + extern int wcmatch(char *s,char *template); + extern int vl_insert(VLINK vl,VDIR1 vd,int allow_conflict); + extern int ul_insert(VLINK ul,VDIR1 vd,VLINK p); + extern int scan_error(char *erst); + + /* + * get_vdir - Get contents of a directory given its location + * + * GET_VDIR takes a directory location, a list of desired + * components, a pointer to a directory structure to be + * filled in, and flags. It then queries the appropriate + * directory server and retrieves the desired information. + * + * ARGS: dhost - Host on which directory resides + * dfile - Directory on that host + * components - The names from the directory we want + * dir - Structure to be filled in + * flags - Options. See FLAGS + * filters - filters to be applied to result + * acomp - Pointer to remaining components + * + * FLAGS: GVD_UNION - Do not expand union links + * GVD_EXPAND - Expand union links locally + * GVD_REMEXP - Request remote expansion (& local if refused) + * GVD_LREMEXP - Request remote expansion of local union links + * GVD_VERIFY - Only verify that args are for a directory + * GVD_ATTRIB - Request attributes from directory server + * GVD_NOSORT - Do not sort links when adding to directory + * + * RETURNS: PSUCCESS (0) or error code + * On some codes addition information in p_err_string + * + * NOTES: If acomp is non-null the string it points to might be modified + * + * If the directory passed as an argument already has + * links or union links, then those lists will be freed + * before the new contents are filled in. + * + * If a filter is passed to the procedure, and application of + * the filter results in additional union link, then those links + * will (or will not) be expanded as specified in the FLAGS field. + * + * If the list of components in NULL, or the null string, then + * get_vdir will return all links in the requested directory. + * + * BUGS: Doesn't process union links yet + * Doesn't process errors returned from server + * Doesn't expand union links if requested to + */ + int get_vdir(char *dhost,char *dfile,char *components,VDIR1 dir,long flags, + VLINK filters,char *acomp) + { + PTEXT request; /* Text of request to dir server */ + PTEXT resp; /* Response from dir server */ + + char ulcomp[MAX_VPATH];/* Work space for new current component */ + char *comp = components; + + VLINK cur_link = NULL;/* Current link being filled in */ + VLINK exp = NULL; /* The current ulink being expanded */ + VLINK pul = NULL; /* Prev union link (insert new one after it) */ + VLINK l; /* Temp link pointer */ + int mcomp; /* Flag - check multiple components */ + int unresp; /* Flag - received unresolved response */ + int getattrib = 0; /* Get attributes from server */ + int vl_insert_flag; /* Flags to vl_insert */ + + int fwdcnt = MAX_FWD_DEPTH; + + int no_links = 0; /* Count of number of links found */ + + char options[40]; /* LIST option */ + char *opt; /* After leading + */ + + PAUTH authinfo; + + /* Treat null string like NULL (return entire directory) */ + if(!components || !*components) comp = NULL; + + if(acomp && !filters) mcomp = 1; + else mcomp = 0; + + if(flags&GVD_ATTRIB) { + getattrib++; + flags &= (~GVD_ATTRIB); + } + + if(flags&GVD_NOSORT) vl_insert_flag = VLI_NOSORT; + else vl_insert_flag = VLI_ALLOW_CONF; + flags &= (~GVD_NOSORT); + + if(filters) comp = NULL; + + perrno = 0; + + authinfo = get_pauth(PFSA_UNAUTHENTICATED); + + *options = '\0'; + + if(getattrib) { + strcat(options,"+ATTRIBUTES"); + flags &= (~GVD_ATTRIB); + } + + if(!filters) { /* Can't do remote expansion if filters to be applied */ + if(flags == GVD_REMEXP) strcat(options,"+EXPAND"); + if(flags == GVD_LREMEXP) strcat(options,"+LEXPAND"); + } + + /* If all we are doing is verifying that dfile is a directory */ + /* then we do not want a big response from the directory */ + /* server. A NOT-FOUND is sufficient. */ + if(flags == GVD_VERIFY) + #ifdef NEWVERIFYOPT + strcat(options,"+VERIFY"); + #else + comp = "%#$PRobably_nOn_existaNT$#%"; + #endif + + if(*options) opt = options+1; + else opt = "''"; + + startover: + request = ptalloc(); + + sprintf(request->start, + "VERSION %d\nAUTHENTICATOR %s %s\nDIRECTORY ASCII %s\nLIST %s COMPONENTS %s%s%s\n", + VFPROT_VNO, authinfo->auth_type, authinfo->authenticator, + dfile,opt, (comp ? comp : ""), (mcomp ? "/" : ""), + (mcomp ? acomp : "")); + + request->length = strlen(request->start); + + #ifdef DEBUG + if(pfs_debug > 2) + fprintf(stderr,"Sending message to dirsrv:\n%s",request->start); + #endif + + #if defined(MSDOS) + resp = dirsend(request,dhost,0L); + #else + resp = dirsend(request,dhost,0); + #endif + + #ifdef DEBUG + if(pfs_debug && (resp == NULL)) { + fprintf(stderr,"Dirsend failed: %d\n",perrno); + } + #endif + + /* If we don't get a response, then if the requested */ + /* directory, return error, if a ulink, mark it unexpanded */ + if(resp == NULL) { + if(exp) exp->expanded = FAILED; + else return(perrno); + } + + unresp = 0; + + /* Here we must parse reponse and put in directory */ + /* While looking at each packet */ + while(resp) { + PTEXT vtmp; + char *line; + + vtmp = resp; + #ifdef DEBUG + if(pfs_debug > 3) fprintf(stderr,"%s\n",resp->start); + #endif + /* Look at each line in packet */ + for(line = resp->start;line != NULL;line = nxtline(line)) { + switch (*line) { + + /* Temporary variables to hold link info */ + char l_linktype; + char l_name[MAX_DIR_LINESIZE]; + char l_type[MAX_DIR_LINESIZE]; + char l_htype[MAX_DIR_LINESIZE]; + char l_host[MAX_DIR_LINESIZE]; + char l_ntype[MAX_DIR_LINESIZE]; + char l_fname[MAX_DIR_LINESIZE]; + int l_version; + char t_unresolved[MAX_DIR_LINESIZE]; + int l_magic; + int tmp; + + case 'L': /* LINK or LINK-INFO */ + if(strncmp(line,"LINK-INFO",9) == 0) { + PATTRIB at; + PATTRIB last_at; + at = parse_attribute(line); + if(!at) break; + + /* Cant have link info without a link */ + if(!cur_link) { + perrno = DIRSRV_BAD_FORMAT; + atfree(at); + break; + } + + if(cur_link->lattrib) { + last_at = cur_link->lattrib; + while(last_at->next) last_at = last_at->next; + at->previous = last_at; + last_at->next = at; + } + else { + cur_link->lattrib = at; + at->previous = NULL; + } + break; + } + + /* Not LINK-INFO, must be LINK - if not check for error */ + if(strncmp(line,"LINK",4) != 0) goto scanerr; + + /* If only verifying, don't want to change dir */ + if(flags == GVD_VERIFY) { + break; + } + /* If first link and some links in dir, free them */ + if(!no_links++) { + if(dir->links) vllfree(dir->links); dir->links=NULL; + if(dir->ulinks) vllfree(dir->ulinks); dir->ulinks=NULL; + } + + cur_link = vlalloc(); + + /* parse and insert file info */ + tmp = sscanf(line,"LINK %c %s %s %s %s %s %s %d %d", &l_linktype, + l_type, l_name, l_htype, l_host, + l_ntype, l_fname, &(cur_link->version), + &(cur_link->f_magic_no)); + + if(tmp != 9) { + perrno = DIRSRV_BAD_FORMAT; + vlfree(cur_link); + break; + } + + cur_link->linktype = l_linktype; + cur_link->type = stcopyr(l_type,cur_link->type); + cur_link->name = stcopyr(unquote(l_name),cur_link->name); + cur_link->hosttype = stcopyr(l_htype,cur_link->hosttype); + cur_link->host = stcopyr(l_host,cur_link->host); + cur_link->nametype = stcopyr(l_ntype,cur_link->nametype); + cur_link->filename = stcopyr(l_fname,cur_link->filename); + + /* Double check to make sure we don't get */ + /* back unwanted components */ + /* OK to keep if special (URP) links */ + /* or if mcomp specified */ + if(!mcomp && (cur_link->linktype == 'L') && + (!wcmatch(cur_link->name,comp))) { + vlfree(cur_link); + break; + } + + /* If other optional info was sent back, it must */ + /* also be parsed before inserting link *** */ + + + if(cur_link->linktype == 'L') + vl_insert(cur_link,dir,vl_insert_flag); + else { + tmp = ul_insert(cur_link,dir,pul); + + /* If inserted after pul, next one after cur_link */ + if(pul && (!tmp || (tmp == UL_INSERT_SUPERSEDING))) + pul = cur_link; + } + + break; + + case 'F': /* FILTER, FAILURE or FORWARDED*/ + /* FORWARDED */ + if(strncmp(line,"FORWARDED",9) == 0) { + if(fwdcnt-- <= 0) { + ptlfree(resp); + perrno = PFS_MAX_FWD_DEPTH; + return(perrno); + } + /* parse and start over */ + + tmp = sscanf(line,"FORWARDED %s %s %s %s %d %d", + l_htype,l_host,l_ntype,l_fname, + &l_version, &l_magic); + + dhost = stcopy(l_host); + dfile = stcopy(l_fname); + + if(tmp < 4) { + perrno = DIRSRV_BAD_FORMAT; + break; + } + + ptlfree(resp); + goto startover; + } + if(strncmp(line,"FILTER",6) != 0) goto scanerr; + break; + + + case 'M': /* MULTI-PACKET (processed by dirsend) */ + case 'P': /* PACKET (processed by dirsend) */ + break; + + case 'N': /* NOT-A-DIRECTORY or NONE-FOUND */ + /* NONE-FOUND, we just have no links to insert */ + /* It is not an error, but we must clear any */ + /* old links in the directory arg */ + if(strncmp(line,"NONE-FOUND",10) == 0) { + /* If only verifying, don't want to change dir */ + if(flags == GVD_VERIFY) { + break; + } + + /* If first link and some links in dir, free them */ + if(!no_links++) { + if(dir->links) vllfree(dir->links); + if(dir->ulinks) vllfree(dir->ulinks); + dir->links = NULL; + dir->ulinks = NULL; + } + break; + } + /* If NOT-A-DIRECTORY or anything else, scan error */ + goto scanerr; + + case 'U': /* UNRESOLVED */ + if(strncmp(line,"UNRESOLVED",10) != 0) { + goto scanerr; + } + tmp = sscanf(line,"UNRESOLVED %s", t_unresolved); + if(tmp < 1) { + perrno = DIRSRV_BAD_FORMAT; + break; + } + /* If multiple components were resolved */ + if(strlen(t_unresolved) < strlen(acomp)) { + strcpy(ulcomp,acomp); + /* ulcomp is the components that were resolved */ + *(ulcomp+strlen(acomp)-strlen(t_unresolved)-1) = '\0'; + /* Comp gets the last component resolved */ + comp = strrchr(ulcomp,(int) '/'); + if(comp) comp++; + else comp = ulcomp; + /* Let rd_vdir know what remains */ + strcpy(acomp,t_unresolved); + } + unresp = 1; + break; + + case 'V': /* VERSION-NOT-SUPPORTED */ + if(strncmp(line,"VERSION-NOT-SUPPORTED",21) == 0) { + perrno = DIRSRV_BAD_VERS; + return(perrno); + } + goto scanerr; + + scanerr: + default: + if(*line && (tmp = scan_error(line))) { + ptlfree(resp); + return(tmp); + } + break; + } + } + + resp = resp->next; + + ptfree(vtmp); + } + + /* We sent multiple components and weren't told any */ + /* were unresolved */ + if(mcomp && !unresp) { + /* ulcomp is the components that were resolved */ + strcpy(ulcomp,acomp); + /* Comp gets the last component resolved */ + comp = strrchr(ulcomp,(int) '/'); + if(comp) comp++; + else comp = ulcomp; + /* If we have union links to resolve, only one component remains */ + mcomp = 0; + /* Let rd_vdir know what remains */ + *acomp = '\0'; + } + + /* If only verifying, we already know it is a directory */ + if(flags == GVD_VERIFY) return(PSUCCESS); + + /* Don't return if matching was delayed by the need to filter */ + /* if FIND specified, and dir->links is non null, then we have */ + /* found a match, and should return. */ + if((flags & GVD_FIND) && dir->links && (!filters)) + return(PSUCCESS); + + /* If expand specified, and ulinks must be expanded, making sure */ + /* that the order of the links is maintained properly */ + + expand_ulinks: + + if((flags != GVD_UNION) && (flags != GVD_VERIFY)) { + + l = dir->ulinks; + + /* Find first unexpanded ulink */ + while(l && l->expanded && (l->linktype == 'U')) l = l->next; + + /* Only expand if a FILE or DIRECTORY - Mark as */ + /* failed otherwise */ + /* We must still add support for symbolic ulinks */ + if(l) { + if ((strcmp(l->type,"DIRECTORY") == 0) || + (strcmp(l->type,"FILE") == 0)) { + l->expanded = TRUE; + exp = l; + pul = l; + dhost = l->host; + dfile = l->filename; + goto startover; /* was get_contents; */ + } + else l->expanded = FAILED; + } + } + + /* Double check to make sure we don't get */ + /* back unwanted components */ + /* OK to keep if special (URP) links */ + if(components && *components) { + l = dir->links; + while(l) { + VLINK ol; + if((l->linktype == 'L') && (!wcmatch(l->name,components))) { + if(l == dir->links) + dir->links = l->next; + else l->previous->next = l->next; + if(l->next) l->next->previous = l->previous; + ol = l; + l = l->next; + vlfree(ol); + } + else l = l->next; + } + } + + return(PSUCCESS); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/patchlevel.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/patchlevel.h:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/patchlevel.h Tue Oct 5 13:19:57 2004 *************** *** 0 **** --- 1,18 ---- + /* + * Archie v1.3 + * + * History: + * + * 01/10/92 v1.3.1 - Release. + * 01/09/92 v1.3 - Release. + * 12/13/91 - added UCX support + * 12/03/91 - added CUTCP support + * 11/20/91 v1.2 - Release. + * 11/18/91 - ported to DOS & OS/2 + * 11/12/91 - finally got to test under Multinet 3.0 + * 10/03/91 - replaced regex.c for oz + * 09/25/91 - added Wollongong support + * 08/30/91 - ported to VMS + * 08/20/91 v1.1 - Major revisions + * 07/31/91 v1.0 - Original + */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pauthent.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pauthent.h:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pauthent.h Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,45 ---- + /* + * Copyright (c) 1989, 1990, 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + */ + + #include + + #define PFSA_UNAUTHENTICATED 1 + + struct pfs_auth_info { + char auth_type[100]; + char authenticator[250]; + }; + + typedef struct pfs_auth_info *PAUTH; + typedef struct pfs_auth_info PAUTH_ST; + + PAUTH get_pauth(); + + #ifndef VMS + # ifndef IN_H + # include + # define IN_H + # endif + #else + # ifndef _ARCHIE_VMS + # include + # endif + #endif + + struct client_info { + int ainfo_type; + char *auth_type; + char *authenticator; + char *userid; + short port; + struct in_addr haddr; + struct pfs_auth_info *previous; + struct pfs_auth_info *next; + }; + + typedef struct client_info *CINFO; + typedef struct client_info CINFO_ST; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pcompat.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pcompat.h:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pcompat.h Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,45 ---- + /* + * Copyright (c) 1989, 1990 by the University of Washington + * + * For copying and distribution information, please see the file + * . + */ + + #include + + /* + * pcompat.h - Definitions for compatability library + * + * This file contains the defintions used by the compatability + * library. Among the definitions are the possible values for + * pfs_disable_flag. This file also contains the external + * declaration of that variable. Note, however that the + * the module pfs_disable_flag.o is included in libpfs.a + * because some of the routines in that library set it. + * The only place it is checked, however, is in pfs_access, + * found in libpcompat.a + * + */ + + extern int pfs_default; + extern int pfs_enable; + + /* Definitions for values of pfs_enable */ + #define PMAP_DISABLE 0 + #define PMAP_ENABLE 1 + #define PMAP_COLON 2 + #define PMAP_ATSIGN_NF 3 + #define PMAP_ATSIGN 4 + + #define DISABLE_PFS(stmt) {int DpfStmp; DpfStmp = pfs_enable;\ + pfs_enable = PMAP_DISABLE; \ + stmt; \ + pfs_enable = DpfStmp;} + + /* Definitions for PFS_ACCESS */ + #define PFA_MAP 0 /* Map the file name only */ + #define PFA_CREATE 1 /* Create file if not found */ + #define PFA_CRMAP 2 /* Map file name. Map to new name if not found */ + #define PFA_RO 4 /* Access to file is read only */ + + #define check_pfs_default() if(pfs_default == -1) get_pfs_default() Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/perrmesg.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/perrmesg.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/perrmesg.c Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,182 ---- + /* + * Copyright (c) 1989, 1990, 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + */ + + #include + #include + #include + + /* This file and perrno.h should always be updated simultaneously */ + + int perrno = 0; + int pwarn = 0; + char p_err_string[P_ERR_STRING_SZ]; + char p_warn_string[P_ERR_STRING_SZ]; + + char *p_err_text[256] = { + /* 0 */ "Success (prospero)", + /* 1 */ "Port unknown (dirsend)", + /* 2 */ "Can't open local UDP port (dirsend)", + /* 3 */ "Can't resolve hostname (dirsend)", + /* 4 */ "Unable to send entire message (dirsend)", + /* 5 */ "Timed out (dirsend)", + /* 6 */ "Recvfrom failed (dirsend)", + /* 7 */ "", /* 8 */ "", /* 9 */ "", /* 10 */ "", + /* 11 */ "Sendto failed (reply)", + /* 12 */ "", /* 13 */ "", /* 14 */ "", /* 15 */ "", + /* 16 */ "", /* 17 */ "", /* 18 */ "", /* 19 */ "", + /* 20 */ "", + /* 21 */ "Link already exists (vl_insert)", + /* 22 */ "Link with same name already exists (vl_insert)", + /* 23 */ "", /* 24 */ "", + /* 25 */ "Link already exists (ul_insert)", + /* 26 */ "Replacing existing link (ul_insert)", + /* 27 */ "Previous entry not found in dir->ulinks (ul_insert)", + /* 28 */ "", /* 29 */ "", /* 30 */ "", /* 31 */ "", + /* 32 */ "", /* 33 */ "", /* 34 */ "", /* 35 */ "", + /* 36 */ "", /* 37 */ "", /* 38 */ "", /* 39 */ "", + /* 40 */ "", + /* 41 */ "Temporary not found (rd_vdir)", + /* 42 */ "Namespace not closed with object (rd_vdir)", + /* 43 */ "Alias for namespace not defined (rd_vdir)", + /* 44 */ "Specified namespace not found (rd_vdir)", + /* 45 */ "", /* 46 */ "", /* 47 */ "", /* 48 */ "", + /* 49 */ "", /* 50 */ "", + /* 51 */ "File access method not supported (pfs_access)", + /* 52 */ "", /* 53 */ "", /* 54 */ "", + /* 55 */ "Pointer to cached copy - delete on close (pmap_cache)", + /* 56 */ "Unable to retrieve file (pmap_cache)", + /* 57 */ "", /* 58 */ "", /* 59 */ "", /* 60 */ "", + /* 61 */ "Directory already exists (mk_vdir)", + /* 62 */ "Link with same name already exists (mk_vdir)", + /* 63 */ "", /* 64 */ "", + /* 65 */ "Not a virtual system (vfsetenv)", + /* 66 */ "Can't find directory (vfsetenv)", + /* 67 */ "", /* 68 */ "", /* 69 */ "", /* 70 */ "", + /* 71 */ "Link already exists (add_vlink)", + /* 72 */ "Link with same name already exists (add_vlink)", + /* 73 */ "", /* 74 */ "", /* 75 */ "", /* 76 */ "", + /* 77 */ "", /* 78 */ "", /* 79 */ "", /* 80 */ "", + /* 81 */ "", /* 82 */ "", /* 83 */ "", /* 84 */ "", + /* 85 */ "", /* 86 */ "", /* 87 */ "", /* 88 */ "", + /* 89 */ "", /* 90 */ "", /* 91 */ "", /* 92 */ "", + /* 93 */ "", /* 94 */ "", /* 95 */ "", /* 96 */ "", + /* 97 */ "", /* 98 */ "", /* 99 */ "", /* 100 */ "", + /* 101 */ "", /* 102 */ "", /* 103 */ "", /* 104 */ "", + /* 105 */ "", /* 106 */ "", /* 107 */ "", /* 108 */ "", + /* 109 */ "", /* 110 */ "", /* 111 */ "", /* 112 */ "", + /* 113 */ "", /* 114 */ "", /* 115 */ "", /* 116 */ "", + /* 117 */ "", /* 118 */ "", /* 119 */ "", /* 120 */ "", + /* 121 */ "", /* 122 */ "", /* 123 */ "", /* 124 */ "", + /* 125 */ "", /* 126 */ "", /* 127 */ "", /* 128 */ "", + /* 129 */ "", /* 130 */ "", /* 131 */ "", /* 132 */ "", + /* 133 */ "", /* 134 */ "", /* 135 */ "", /* 136 */ "", + /* 137 */ "", /* 138 */ "", /* 139 */ "", /* 140 */ "", + /* 141 */ "", /* 142 */ "", /* 143 */ "", /* 144 */ "", + /* 145 */ "", /* 146 */ "", /* 147 */ "", /* 148 */ "", + /* 149 */ "", /* 150 */ "", /* 151 */ "", /* 152 */ "", + /* 153 */ "", /* 154 */ "", /* 155 */ "", /* 156 */ "", + /* 157 */ "", /* 158 */ "", /* 159 */ "", /* 160 */ "", + /* 161 */ "", /* 162 */ "", /* 163 */ "", /* 164 */ "", + /* 165 */ "", /* 166 */ "", /* 167 */ "", /* 168 */ "", + /* 169 */ "", /* 170 */ "", /* 171 */ "", /* 172 */ "", + /* 173 */ "", /* 174 */ "", /* 175 */ "", /* 176 */ "", + /* 177 */ "", /* 178 */ "", /* 179 */ "", /* 180 */ "", + /* 181 */ "", /* 182 */ "", /* 183 */ "", /* 184 */ "", + /* 185 */ "", /* 186 */ "", /* 187 */ "", /* 188 */ "", + /* 189 */ "", /* 190 */ "", /* 191 */ "", /* 192 */ "", + /* 193 */ "", /* 194 */ "", /* 195 */ "", /* 196 */ "", + /* 197 */ "", /* 198 */ "", /* 199 */ "", /* 200 */ "", + /* 201 */ "", /* 202 */ "", /* 203 */ "", /* 204 */ "", + /* 205 */ "", /* 206 */ "", /* 207 */ "", /* 208 */ "", + /* 209 */ "", /* 210 */ "", /* 211 */ "", /* 212 */ "", + /* 213 */ "", /* 214 */ "", /* 215 */ "", /* 216 */ "", + /* 217 */ "", /* 218 */ "", /* 219 */ "", /* 220 */ "", + /* 221 */ "", /* 222 */ "", /* 223 */ "", /* 224 */ "", + /* 225 */ "", /* 226 */ "", /* 227 */ "", /* 228 */ "", + /* 229 */ "", + /* 230 */ "File not found (prospero)", + /* 231 */ "Directory not found (prospero)", + /* 232 */ "Symbolic links nested too deep (prospero)", + /* 233 */ "Environment not initialized - source vfsetup.source then run vfsetup", + /* 234 */ "Can't traverse an external file (prospero)", + /* 235 */ "Forwarding chain is too long (prospero)", + /* 236 */ "", /* 237 */ "", /* 238 */ "", /* 239 */ "", + /* 240 */ "", /* 241 */ "", + /* 242 */ "Authentication required (prospero server)", + /* 243 */ "Not authorized (prospero server)", + /* 244 */ "Not found (prospero server)", + /* 245 */ "Bad version number (prospero server)", + /* 246 */ "Not a directory (prospero server)", + /* 247 */ "Already exists (prospero server)", + /* 248 */ "Link with same name already exists (prospero server)", + /* 249 */ "", /* 250 */ "", + /* 251 */ "Command not implemented on server (dirsrv)", + /* 252 */ "Bad format for response (dirsrv)", + /* 253 */ "Protocol error (prospero server)", + /* 254 */ "Unspecified server failure (prospero server)", + /* 255 */ "Generic Failure (prospero)"}; + + char *p_warn_text[256] = { + /* 0 */ "No warning", + /* 1 */ "You are using an old version of this program", + /* 2 */ "From server", + /* 3 */ "Unrecognized line in response from server", + /* 4-254 */ "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + /* 255 */ ""}; + + #ifndef ARCHIE + + void perrmesg(char *prefix,int no,char *text) + { + fprintf(stderr,"%s%s%s%s\n", (prefix ? prefix : ""), + (no ? p_err_text[no] : p_err_text[perrno]), + ((text ? (*text ? " - " : "") : + (!no && *p_err_string ? " - " : ""))), + (text ? text : (no ? "" : p_err_string))); + } + + void sperrmesg(char *buf,char *prefix,int no,char *text) + { + sprintf(buf,"%s%s%s%s\n", (prefix ? prefix : ""), + (no ? p_err_text[no] : p_err_text[perrno]), + ((text ? (*text ? " - " : "") : + (!no && *p_err_string ? " - " : ""))), + (text ? text : (no ? "" : p_err_string))); + } + + void pwarnmesg(char *prefix,int no,char *text) + { + fprintf(stderr,"%s%s%s%s\n", (prefix ? prefix : ""), + (no ? p_warn_text[no] : p_warn_text[pwarn]), + ((text ? (*text ? " - " : "") : + (!no && *p_warn_string ? " - " : ""))), + (text ? text : (no ? "" : p_warn_string))); + } + + void spwarnmesg(char *buf,char *prefix,int no,char *text) + { + sprintf(buf,"%s%s%s%s\n", (prefix ? prefix : ""), + (no ? p_warn_text[no] : p_warn_text[pwarn]), + ((text ? (*text ? " - " : "") : + (!no && *p_warn_string ? " - " : ""))), + (text ? text : (no ? "" : p_warn_string))); + } + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/perrno.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/perrno.h:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/perrno.h Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,123 ---- + /* + * Copyright (c) 1989, 1990 by the University of Washington + * + * For copying and distribution information, please see the file + * . + */ + + #include + + /* this file and p_err_text.c should be updated simultaneously */ + + /* + * perrno.h - definitions for perrno + * + * This file contains the declarations and defintions of of the external + * error values in which errors are returned by the pfs and psrv + * libraries. + */ + + #define P_ERR_STRING_SZ 100 /* Size of error string */ + + extern int perrno; + extern char p_err_string[]; + extern char *p_err_text[]; + + extern int pwarn; + extern char p_warn_string[]; + extern char *p_warn_text[]; + + /* Error codes returned or found in verrno */ + + #ifndef PSUCCESS + #define PSUCCESS 0 + #endif + + /* dirsend (perrno) */ + #define DIRSEND_PORT_UNKN 1 /* DIRSRV UDP port unknown */ + #define DIRSEND_UDP_CANT 2 /* Can't open local UDP port */ + #define DIRSEND_BAD_HOSTNAME 3 /* Can't resolve hostname */ + #define DIRSEND_NOT_ALL_SENT 4 /* Didn't send entire message */ + #define DIRSEND_SELECT_FAILED 5 /* Select failed */ + #define DIRSEND_BAD_RECV 6 /* Recvfrom failed */ + + /* reply */ + #define REPLY_NOTSENT 11 /* Reply: sendto failed */ + + /* vl_insert */ + #define VL_INSERT_ALREADY_THERE 21 /* Link already exists */ + #define VL_INSERT_CONFLICT 22 /* Link exists with same name */ + + /* ul_insert */ + #define UL_INSERT_ALREADY_THERE 25 /* Link already exists */ + #define UL_INSERT_SUPERSEDING 26 /* Replacing existing link */ + #define UL_INSERT_POS_NOTFOUND 27 /* Prv entry not in dir->ulinks */ + + /* rd_vdir */ + #define RVD_DIR_NOT_THERE 41 /* Temporary NOT_FOUND */ + #define RVD_NO_CLOSED_NS 42 /* Namespace not closed w/ object:: */ + #define RVD_NO_NS_ALIAS 43 /* No alias for namespace NS#: */ + #define RVD_NS_NOT_FOUND 44 /* Specified namespace not found */ + + /* pfs_access */ + #define PFSA_AM_NOT_SUPPORTED 51 /* Access method not supported */ + + /* pmap_cache */ + #define PMC_DELETE_ON_CLOSE 55 /* Delete cached copy on close */ + #define PMC_RETRIEVE_FAILED 56 /* Unable to retrieve file */ + + /* mk_vdir */ + /* #define MKVD_ALREADY_EXISTS 61 Directory already exists */ + /* #define MKVD_NAME_CONFLICT 62 Link with name already exists */ + + /* vfsetenv */ + #define VFSN_NOT_A_VS 65 /* Not a virtual system */ + #define VFSN_CANT_FIND_DIR 66 /* Not a virtual system */ + + /* add_vlink */ + /* #define ADDVL_ALREADY_EXISTS 71 Directory already exists */ + /* #define ADDVL_NAME_CONFLICT 72 Link with name already exists */ + + /* Local error codes on server */ + + /* dsrdir */ + #define DSRDIR_NOT_A_DIRECTORY 111 /* Not a directory name */ + /* dsrfinfo */ + #define DSRFINFO_NOT_A_FILE 121 /* Object not found */ + #define DSRFINFO_FORWARDED 122 /* Object has moved */ + + /* Error codes that may be returned by various procedures */ + #define PFS_FILE_NOT_FOUND 230 /* File not found */ + #define PFS_DIR_NOT_FOUND 231 /* Directory in path not found */ + #define PFS_SYMLINK_DEPTH 232 /* Max sym-link depth exceeded */ + #define PFS_ENV_NOT_INITIALIZED 233 /* Can't read environment */ + #define PFS_EXT_USED_AS_DIR 234 /* Can't use externals as dirs */ + #define PFS_MAX_FWD_DEPTH 235 /* Exceeded max forward depth */ + + /* Error codes returned by directory server */ + /* some of these duplicate errors from individual routines */ + /* some of those error codes should be eliminated */ + #define DIRSRV_AUTHENT_REQ 242 /* Authentication required */ + #define DIRSRV_NOT_AUTHORIZED 243 /* Not authorized */ + #define DIRSRV_NOT_FOUND 244 /* Not found */ + #define DIRSRV_BAD_VERS 245 + #define DIRSRV_NOT_DIRECTORY 246 + #define DIRSRV_ALREADY_EXISTS 247 /* Identical link already exists */ + #define DIRSRV_NAME_CONFLICT 248 /* Link with name already exists */ + + #define DIRSRV_UNIMPLEMENTED 251 /* Unimplemented command */ + #define DIRSRV_BAD_FORMAT 252 + #define DIRSRV_ERROR 253 + #define DIRSRV_SERVER_FAILED 254 /* Unspecified server failure */ + + #ifndef PFAILURE + #define PFAILURE 255 + #endif + + /* Warning codes */ + + #define PNOWARN 0 /* No warning indicated */ + #define PWARN_OUT_OF_DATE 1 /* Software is out of date */ + #define PWARN_MSG_FROM_SERVER 2 /* Warning in p_warn_string */ + #define PWARN_UNRECOGNIZED_RESP 3 /* Unrecognized line in response */ + #define PWARNING 255 /* Warning in p_warn_string */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pfs.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pfs.h:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pfs.h Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,376 ---- + /* + * Copyright (c) 1989, 1990, 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + * + * v1.2.0 - 11/19/91 (mmt) - added MSDOS & OS2 stuff + * v1.1.2 - 08/30/91 (bpk) - added VMS support + * v1.1.1 - 08/20/91 (bpk) - 4.2 -> 4.2B + */ + + #include + + #ifdef VMS + # include + #else /* not VMS */ + # ifndef _TYPES_ + # include + # endif /* _TYPES_ */ + # ifndef IN_H + # include + # define IN_H + # endif + #endif /* VMS */ + + #ifndef NULL + # ifdef MSDOS + # include + # else + # define NULL 0 + # endif /* MSDOS */ + #endif /* NULL */ + + #define PFS_RELEASE "Beta.4.2D" + /* moved up for vdir_init */ + #define ZERO(p) bzero((char *)(p), sizeof(*(p))) + + /* General Definitions */ + + #define MAX_PTXT_LEN 1250 /* Max length of PTEXT structure */ + #define MAX_PTXT_HDR 32 /* Max offset for start */ + #define P_ERR_STRING_SZ 100 /* Size of error string */ + #define MAX_VPATH 1024 /* Max length of virtual pathname */ + + /* Definition of text structure used to pass text around */ + + struct ptext { + int length; /* Length of text (from start) */ + char *start; /* Start of text */ + char dat[MAX_PTXT_LEN+2*MAX_PTXT_HDR];/* The data itself */ + unsigned long mbz; /* ZERO to catch runaway strings */ + struct ptext *previous; /* Previous element in list */ + struct ptext *next; /* Next element in linked list */ + int seq; /* Sequence Number */ + }; + + typedef struct ptext *PTEXT; + typedef struct ptext PTEXT_ST; + + /* Request structure: maintains information about server requests */ + struct preq { + int cid; /* Connection ID */ + short priority; /* Connection priority */ + int pf_priority; /* Priority assigned by pri_func */ + int recv_tot; /* Total # of packets received */ + int trns_tot; /* Total # of packets to transmit */ + struct ptext *cpkt; /* Current packet being filled in */ + struct ptext *recv; /* Received packets */ + struct ptext *trns; /* Transmitted packets */ + int rcvd_thru; /* Received all packets through # */ + struct preq *previous; /* Previous element in list */ + struct preq *next; /* Next element in linked list */ + struct sockaddr_in fromto; /* Sender/Destination */ + }; + + typedef struct preq *PREQ; + typedef struct preq PREQ_ST; + + + /* Definition of structure containing information on virtual link */ + + struct vlink { + int dontfree; /* Flag: don't free this link */ + char *name; /* Component of path name */ + char linktype; /* L = Link, U = Union, N= Native */ + int expanded; /* Has a union link been expanded */ + char *type; /* Type of object pointed to */ + struct vlink *filters; /* Filters associated with link */ + struct vlink *replicas; /* Replicas (* see comment below) */ + char *hosttype; /* Type of hostname */ + char *host; /* Files physical location */ + char *nametype; /* Type of filename */ + char *filename; /* System level filename */ + long version; /* Version number of destination */ + long f_magic_no; /* File's magic number */ + struct acl *acl; /* ACL for link */ + long dest_exp; /* Expiration for dest of link */ + long link_exp; /* Expiration of link itself */ + char *args; /* Arguments if this is a filter */ + struct pattrib *lattrib; /* Attributes associated w/ link */ + struct pfile *f_info; /* Info to be assoicated w/ file */ + struct vlink *previous; /* Previous elt in linked list */ + struct vlink *next; /* Next element in linked list */ + }; + + typedef struct vlink *VLINK; + typedef struct vlink VLINK_ST; + + /* * Note that vlink->replicas is not really a list of replicas of the */ + /* object. Instead, it is a list of the objects returned during name */ + /* resolution that share the same name as the current object. Such */ + /* an object should only be considered a replica if it also shares */ + /* the same non-zero magic number. */ + + /* Definition of structure continiaing virtual directory information */ + + struct vdir { + int version; /* Version of local directory fmt */ + int inc_native; /* Include the native directory */ + long magic_no; /* Magic number of current file */ + struct acl *dacl; /* Default acl for links in dir */ + struct pfile *f_info; /* Directory file info */ + struct vlink *links; /* The directory entries */ + struct vlink *lastlink; /* Last directory entry */ + struct vlink *ulinks; /* The entries for union links */ + struct vdir *previous; /* Previous element in linked list */ + struct vdir *next; /* Next element in linked list */ + }; + + typedef struct vdir *VDIR1; + typedef struct vdir VDIR_ST; + + /* Initialize directory */ + #define vdir_init(dir) ZERO(dir) + /* XXX: was + + dir->version = 0; dir->inc_native = 0; \ + dir->magic_no = 0; dir->f_info = NULL; \ + dir->links = NULL; dir->lastlink = NULL; \ + dir->ulinks = NULL; dir->dacl = NULL; \ + dir->previous = NULL; dir->next = NULL; + */ + + #define vdir_copy(d1,d2) d2->version = d1->version; \ + d2->inc_native = d1->inc_native; \ + d2->magic_no = d1->magic_no; \ + d2->f_info = d1->f_info; \ + d2->links = d1->links; \ + d2->lastlink = d1->lastlink; \ + d2->ulinks = d1->ulinks; \ + d2->dacl = d1->dacl; \ + d2->previous = d1->previous; \ + d2->next = d1->next; + + /* Values of ->inc_native in vdir structure */ + #define VDIN_REALONLY -1 /* Include native files, but not . and .. */ + #define VDIN_NONATIVE 0 /* Do not include files from native directory */ + #define VDIN_INCLNATIVE 1 /* Include files from native directory */ + #define VDIN_NATIVEONLY 2 /* All entries in directory are from native dir */ + #define VDIN_PSEUDO 3 /* Directory is not real */ + + + /* Definition of structure containing information on a specific file */ + + union avalue { + char *ascii; /* Character string */ + struct vlink *link; /* A link */ + }; + + + struct pattrib { + char precedence; /* Precedence for link attribute */ + char *aname; /* Name of the attribute */ + char *avtype; /* Type of the attribute value */ + union avalue value; /* Attribute Value */ + struct pattrib *previous; /* Previous element in linked list */ + struct pattrib *next; /* Next element in linked list */ + }; + + typedef struct pattrib *PATTRIB; + typedef struct pattrib PATTRIB_ST; + + #define ATR_PREC_OBJECT 'O' /* Authoritative answer for object */ + #define ATR_PREC_LINK 'L' /* Authoritative answer for link */ + #define ATR_PREC_CACHED 'C' /* Object info cached w/ link */ + #define ATR_PREC_REPLACE 'R' /* From link (replaces O) */ + #define ATR_PREC_ADD 'A' /* From link (additional value) */ + + /* **** Incomplete **** */ + struct pfile { + int version; /* Version of local finfo format */ + long f_magic_no; /* Magic number of current file */ + long exp; /* Expiration date of timeout */ + long ttl; /* Time to live after reference */ + long last_ref; /* Time of last reference */ + struct vlink *forward; /* List of forwarding pointers */ + struct vlink *backlinks; /* Partial list of back links */ + struct pattrib *attributes; /* List of file attributes */ + struct pfile *previous; /* Previous element in linked list */ + struct pfile *next; /* Next element in linked list */ + }; + + typedef struct pfile *PFILE; + typedef struct pfile PFILE_ST; + + /* Definition of structure contining an access control list entry */ + + struct acl { + int acetype; /* Access Contol Entry type */ + char *atype; /* Authentication type */ + char *rights; /* Rights */ + char *principals; /* Authorized principals */ + struct restrict *restrictions; /* Restrictions on use */ + struct acl *previous; /* Previous elt in linked list */ + struct acl *next; /* Next element in linked list */ + }; + typedef struct acl *ACL; + typedef struct acl ACL_ST; + + #define ACL_NONE 0 /* Nobody authorized by ths entry */ + #define ACL_DEFAULT 1 /* System default */ + #define ACL_SYSTEM 2 /* System administrator */ + #define ACL_OWNER 3 /* Directory owner */ + #define ACL_DIRECTORY 4 /* Same as directory */ + #define ACL_ANY 5 /* Any user */ + #define ACL_AUTHENT 6 /* Authenticated principal */ + #define ACL_LGROUP 7 /* Local group */ + #define ACL_GROUP 8 /* External group */ + #define ACL_ASRTHOST 10 /* Check host and asserted userid */ + #define ACL_TRSTHOST 11 /* ASRTHOST from privileged port */ + + + /* Definition of structure contining access restrictions */ + /* for future extensions */ + struct restrict { + struct acl *previous; /* Previous elt in linked list */ + struct acl *next; /* Next element in linked list */ + }; + + /* Definitions for send_to_dirsrv */ + #define CLIENT_DIRSRV_TIMEOUT 4 /* time between retries */ + #define CLIENT_DIRSRV_BACKOFF(x) (2 * x) /* Backoff algorithm */ + #define CLIENT_DIRSRV_RETRY 3 /* retry this many times */ + + /* Definitions for rd_vlink and rd_vdir */ + #define SYMLINK_NESTING 10 /* Max nesting depth for sym links */ + + /* Definition fo check_acl */ + #define ACL_NESTING 10 /* Max depth for ACL group nesting */ + + /* Flags for mk_vdir */ + #define MKVD_LPRIV 1 /* Minimize privs for creator in new ACL */ + + /* Flags for get_vdir */ + #define GVD_UNION 0 /* Do not expand union links */ + #define GVD_EXPAND 1 /* Expand union links locally */ + #define GVD_LREMEXP 3 /* Request remote expansion of local links */ + #define GVD_REMEXP 7 /* Request remote expansion of all links */ + #define GVD_VERIFY 8 /* Only verify args are for a directory */ + #define GVD_FIND 16 /* Stop expanding when match is found */ + #define GVD_ATTRIB 32 /* Request attributes from remote server */ + #define GVD_NOSORT 64 /* Do not sort links when adding to dir */ + + /* Flags for rd_vdir */ + #define RVD_UNION GVD_UNION + #define RVD_EXPAND GVD_EXPAND + #define RVD_LREMEXP GVD_LREMEXP + #define RVD_REMEXP GVD_REMEXP + #define RVD_DFILE_ONLY GVD_VERIFY /* Only return ptr to dir file */ + #define RVD_FIND GVD_FIND + #define RVD_ATTRIB GVD_ATTRIB + #define RVD_NOSORT GVD_NOSORT + #define RVD_NOCACHE 128 + + /* Flags for add_vlink */ + #define AVL_UNION 1 /* Link is a union link */ + + /* Flags for vl_insert */ + #define VLI_NOCONFLICT 0 /* Do not insert links w/ conflicting names */ + #define VLI_ALLOW_CONF 1 /* Allow links with conflicting names */ + #define VLI_NOSORT 2 /* Allow conflicts and don't sort */ + + /* Flags for mapname */ + #define MAP_READWRITE 0 /* Named file to be read and written */ + #define MAP_READONLY 1 /* Named file to be read only */ + + /* Flags for modify_acl */ + #define MACL_NOSYSTEM 0x01 + #define MACL_NOSELF 0x02 + #define MACL_DEFAULT 0x08 + #define MACL_SET 0x0C + #define MACL_INSERT 0x14 + #define MACL_DELETE 0x10 + #define MACL_ADD 0x1C + #define MACL_SUBTRACT 0x18 + #define MACL_LINK 0x00 + #define MACL_DIRECTORY 0x20 + #define MACL_OBJECT 0x60 + #define MACL_INCLUDE 0x40 + + #define MACL_OP (MACL_DEFAULT|MACL_SET|MACL_INSERT|\ + MACL_DELETE|MACL_ADD|MACL_SUBTRACT) + + #define MACL_OTYPE (MACL_LINK|MACL_DIRECTORY|MACL_OBJECT|MACL_INCLUDE) + + /* Access methods returned by Pget_am */ + #define P_AM_ERROR 0 + #define P_AM_FTP 1 + #define P_AM_AFTP 2 /* Anonymous FTP */ + #define P_AM_NFS 4 + #define P_AM_KNFS 8 /* Kerberized NFS */ + #define P_AM_AFS 16 + + /* Return codes */ + + #define PSUCCESS 0 + #define PFAILURE 255 + + /* Hush up warnings. */ + void vllfree(); + + /* Procedures in libpfs.a */ + + char *pget_wdhost(), *pget_wdfile(), *pget_wd(), *pget_hdhost(); + char *pget_hdfile(), *pget_hd(), *pget_rdhost(), *pget_rdfile(); + char *pget_dhost(), *pget_dfile(), *pget_vsname(), *nlsindex(); + char *sindex(), *strtok(), *nxtline(), *unquote(), *stcopy(); + char *stcopyr(), *readheader(), *month_sname(); + + long asntotime(); + void procquery(char *host,char *str,int max_hits,int offset, + char query_type,int sortflag,int listflag); + + PTEXT ptalloc(); + PTEXT dirsend(); + void ptfree(); + void ptlfree(); + + PREQ pralloc(); + PREQ get_next_request(); + + VLINK rd_slink(); + VLINK rd_vlink(); + VLINK vl_delete(); + VLINK vlalloc(); + VLINK vlcopy(); + void vlfree(); + + PFILE pfalloc(); + + PATTRIB parse_attribute(); + PATTRIB atalloc(); + PATTRIB pget_at(); + void atfree(); + void atlfree(); + + ACL acalloc(); + ACL get_acl(); + + void stfree(); + + /* Miscellaneous useful definitions */ + #ifndef TRUE + #define TRUE 1 + #define FALSE 0 + #endif + + #define AUTHORIZED 1 + #define NOT_AUTHORIZED 0 + #define NEG_AUTHORIZED -1 + + #ifndef NULL + #define NULL 0 + #endif + + #define FAILED -1 Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pmachine.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pmachine.h:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pmachine.h Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,111 ---- + /* + * Miscellaneous system dependencies. + * + * I kept the name pmachine.h because it was already in all of the files...this + * barely resembles the pmachine.h that comes with the real Prospero, tho. + * + * v1.2.1 - 12/13/91 (bpk) - added 3b2 + * v1.2.0 - 11/19/91 (mmt) - added MSDOS & OS2 stuff + */ + + #ifdef u3b2 + # define USG + # define NOREGEX + # define MAXPATHLEN 1024 /* There's no maxpathlen in any 3b2 .h file. */ + #endif + + #ifdef hpux + # ifndef bcopy + # define FUNCS /* HP/UX 8.0 has the fns. */ + # endif + # define NOREGEX + # define NEED_STRING_H + #endif + + #if defined(USG) || defined(SYSV) + # define FUNCS + #endif + + #ifdef ISC + # define FUNCS + # define STRSPN + # define NOREGEX + #endif + + #ifdef CUTCP + # define FUNCS + # define NOREGEX + # define NEED_STRING_H + # define SELECTARG int + # define MSDOS + #endif + + #ifdef OS2 + # define NOREGEX + # include + #endif + #ifdef MSDOS + # define USG + # define NOREGEX + # include + # include + #endif + + #ifdef _AIX + # ifdef u370 + # define FUNCS + # endif /* AIX/370 */ + # define _NONSTD_TYPES + # define _BSD_INCLUDES + # define NEED_STRING_H + # define NEED_SELECT_H + # define NEED_TIME_H + #endif + + /* ==== */ + #ifdef FUNCS + # define index strchr + /* According to mycroft. */ + # ifdef _IBMR2 + char *strchr(); + # endif + # define rindex strrchr + # ifndef AUX + # define bcopy(a,b,n) memcpy(b,a,n) + # define bzero(a,n) memset(a,0,n) + # ifdef _IBMR2 + char *memset(); + # endif + # endif + #endif + + #if defined(_IBMR2) || defined(_BULL_SOURCE) + # define NEED_SELECT_H + #endif + #if defined(USG) || defined(UTS) + # define NEED_STRING_H + #endif + #if defined(USG) || defined(UTS) || defined(AUX) + # define NEED_TIME_H + #endif + + #ifdef VMS + /* Get the system status stuff. */ + # include + #endif /* VMS */ + + /* + * FD_SET: lib/pfs/dirsend.c, user/vget/ftp.c + */ + #ifndef CUTCP + + #define SELECTARG fd_set + #if !defined(FD_SET) && !defined(VMS) && !defined(NEED_SELECT_H) + #define FD_SETSIZE 32 + #define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS))) + #define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS))) + #define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS))) + #define FD_ZERO(p) bzero((char *)(p), sizeof(*(p))) + #endif + + #endif /* not CUTCP */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pprot.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pprot.h:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/pprot.h Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,59 ---- + /* + * Copyright (c) 1989, 1990, 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + * + * v1.2.0 - 11/19/91 (mmt) - added MSDOS & OS2 stuff + */ + + #include + + #ifndef MAXPATHLEN + # ifdef VMS + # define MAXPATHLEN 32 + # else /* not VMS */ + # if defined(MSDOS) && !defined(OS2) + # define MAXPATHLEN 255 + # else /* not MSDOS */ + # ifdef ISC + # define MAXPATHLEN 512 + # else /* not Interactive..normal! (gasp) */ + # include + # endif /* ISC */ + # endif /* MSDOS && !OS2 */ + # endif /* VMS */ + #endif + + /* Protocol Definitions */ + + #define VFPROT_VNO 1 /* Protocol Version Number */ + + #define DIRSRV_PORT 1525 /* Server port used if not in srvtab */ + #define PROSPERO_PORT 191 /* Officially assigned prived port */ + #define PROS_FIRST_PRIVP 901 /* First privileged port to try */ + #define PROS_NUM_PRIVP 20 /* Number of privileged ports to try */ + + #define MAXPKT 1024 /* Max size of response from server */ + #define SEQ_SIZE 32 /* Max size of sequence text in resp */ + #define MAX_DIR_LINESIZE 160+MAXPATHLEN /* Max linesize in directory */ + + #define MAX_FWD_DEPTH 20 /* Max fwd pointers to follow */ + + #define S_AD_SZ sizeof(struct sockaddr_in) + + /* Replacement for strtok that doesn't keep state. Both the variable */ + /* S and the variable S_next must be defined. To initialize, assign */ + /* the string to be stepped through to S_next, then call get_token on */ + /* S. The first token will be in S, and S_next will point to the next */ + /* token. Like strtok, this macro does modify the string passed to it */ + #define get_token(S,C) \ + S = S/**/_next; \ + if(S) { \ + while(*S == C) S++; \ + S/**/_next = index(S,C); \ + if(S/**/_next) *(S/**/_next++) = '\0'; \ + if(!*S) S = NULL; \ + } + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/procquery.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/procquery.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/procquery.c Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,213 ---- + /* + * procquery.c : Routines for processing results from Archie + * + * Originally part of the Prospero Archie client by Cliff Neuman (bcn at isi.edu). + * Modified by Brendan Kehoe (brendan at cs.widener.edu). + * Re-modified by George Ferguson (ferguson at cs.rochester.edu). + * + * Copyright (c) 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + * + * v1.2.2 - 11/19/91 (mmt) - added MSDOS & OS2 stuff + * v1.2.1 - 10/18/91 (bpk) - warning stuff + * v1.2.0 - 09/20/91 (bpk) - VMS under Multinet 3.0 too + * v1.1.1 - 08/20/91 (bpk) - took out archie_query from error msg + */ + #include + #include + #include + #include + #include + #include + + # include + + extern int client_dirsrv_timeout,client_dirsrv_retry; /* dirsend.c */ + extern char *progname; + + + /* + * Functions defined here + */ + + extern void procquery(char *host,char *str,int max_hits,int offset, + char query_type,int sortflag,int listflag); + + void display_link(VLINK l,int listflag); + + /* + * Data defined here + */ + extern int pwarn, perrno; + #ifdef DEBUG + int pfs_debug; + #endif + static struct tm *presenttime; + static char lastpath[MAX_VPATH] = "\001"; + static char lasthost[MAX_VPATH] = "\001"; + + /* - - - - - - - - */ + /* + * display_link : Prints the contents of the given virtual link. If + * listflag is 0, then this uses last{host,path} to save state + * between calls for a less verbose output. If listflag is non-zero + * then all information is printed every time. + */ + void display_link(VLINK l,int listflag) + { + PATTRIB ap; + char linkpath[MAX_VPATH]; + int dirflag = 0; + #ifdef MSDOS + unsigned long size = 0L; + #else + int size = 0; + #endif + char *modes = ""; + char archie_date[20]; + char *gt_date = ""; + int gt_year = 0; + int gt_mon = 0; + int gt_day = 0; + int gt_hour = 0; + int gt_min = 0; + + /* Initialize local buffers */ + *archie_date = '\0'; + + /* Remember if we're looking at a directory */ + if (sindex(l->type,"DIRECTORY")) + dirflag = 1; + else + dirflag = 0; + + /* Extract the linkpath from the filename */ + strcpy(linkpath,l->filename); + *(linkpath + (strlen(linkpath) - strlen(l->name) - 1)) = '\0'; + + /* Is this a new host? */ + if (strcmp(l->host,lasthost) != 0) { + if (!listflag) + printf("\nHost %s\n\n",l->host); + strcpy(lasthost,l->host); + *lastpath = '\001'; + } + + /* Is this a new linkpath (location)? */ + if(strcmp(linkpath,lastpath) != 0) { + if (!listflag) + printf(" Location: %s\n",(*linkpath ? linkpath : "/")); + strcpy(lastpath,linkpath); + } + + /* Parse the attibutes of this link */ + for (ap = l->lattrib; ap; ap = ap->next) { + if (strcmp(ap->aname,"SIZE") == 0) { + #ifdef MSDOS + sscanf(ap->value.ascii,"%lu",&size); + #else + sscanf(ap->value.ascii,"%d",&size); + #endif + } else if(strcmp(ap->aname,"UNIX-MODES") == 0) { + modes = ap->value.ascii; + } else if(strcmp(ap->aname,"LAST-MODIFIED") == 0) { + gt_date = ap->value.ascii; + sscanf(gt_date,"%4d%2d%2d%2d%2d",>_year, + >_mon, >_day, >_hour, >_min); + if ((12 * (presenttime->tm_year + 1900 - gt_year) + + presenttime->tm_mon - gt_mon) > 6) + sprintf(archie_date,"%s %2d %4d",month_sname(gt_mon), + gt_day, gt_year); + else + sprintf(archie_date,"%s %2d %02d:%02d",month_sname(gt_mon), + gt_day, gt_hour, gt_min); + } + } + + /* Print this link's information */ + if (listflag) + #if defined(MSDOS) + printf("%s %6lu %s %s%s\n",gt_date,size,l->host,l->filename, + (dirflag ? "/" : "")); + #else + printf("%s %6d %s %s%s\n",gt_date,size,l->host,l->filename, + (dirflag ? "/" : "")); + #endif + else + #ifdef MSDOS + printf(" %9s %s %10lu %s %s\n",(dirflag ? "DIRECTORY" : "FILE"), + modes,size,archie_date,l->name); + #else + printf(" %9s %s %10d %s %s\n",(dirflag ? "DIRECTORY" : "FILE"), + modes,size,archie_date,l->name); + #endif /* MSDOS */ + + + /* Free the attibutes */ + atlfree(l->lattrib); + l->lattrib = NULL; + } + + /* - - - - - - - - */ + /* + * procquery : Process the given query and display the results. If + * sortflag is non-zero, then the results are sorted by increasing + * date, else by host/filename. If listflag is non-zero then each + * entry is printed on a separate, complete line. Note that listflag + * is ignored by xarchie. + */ + void procquery(char *host,char *str,int max_hits,int offset,char query_type, + int sortflag,int listflag) + { + VLINK l; + long now; + + /* initialize data structures for this query */ + (void)time(&now); + presenttime = localtime(&now); + + /* Do the query */ + if (sortflag == 1) + l = archie_query(host,str,max_hits,offset,query_type,AQ_INVDATECMP,0); + else + l = archie_query(host,str,max_hits,offset,query_type,NULL,0); + + /* Error? */ + if (perrno != PSUCCESS) { + if (p_err_text[perrno]) { + if (*p_err_string) + fprintf(stderr, "%s: failed: %s - %s\n", progname, + p_err_text[perrno], p_err_string); + else + fprintf(stderr, "%s failed: %s\n", progname, p_err_text[perrno]); + } else + fprintf(stderr, "%s failed: Undefined error %d (prospero)", + (char*) perrno,0); + } + + /* Warning? */ + if (pwarn != PNOWARN) { + if (*p_warn_string) + fprintf(stderr, "%s: Warning! %s - %s\n", progname, + p_warn_text[pwarn], p_warn_string); + else + fprintf(stderr, "%s: Warning! %s\n", progname, p_warn_text[pwarn]); + } + + + /* Display the results */ + + if (l == (VLINK)NULL && pwarn == PNOWARN && perrno == PSUCCESS) { + if (! listflag) puts ("No matches."); + exit (1); + } + + *lasthost = '\001'; + *lastpath = '\001'; + while (l != NULL) { + display_link(l,listflag); + l = l->next; + } + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/ptalloc.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/ptalloc.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/ptalloc.c Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,88 ---- + /* + * Copyright (c) 1989, 1990, 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + * + * v1.2.0 - 11/19/91 (mmt) - added MSDOS & OS2 stuff + */ + + #include + #include + #include + + #include + #include /* for correct definition of ZERO */ + #ifdef MSDOS + # define free _pfree /* otherwise we get conflicts with free() */ + #endif + + static PTEXT free1 = NULL; + int ptext_count = 0; + int ptext_max = 0; + + /* + * ptalloc - allocate and initialize ptext structure + * + * PTALLOC returns a pointer to an initialized structure of type + * PTEXT. If it is unable to allocate such a structure, it + * returns NULL. + */ + + extern void bzero(char *b,int length); + + PTEXT ptalloc(void) + { + PTEXT vt; + if(free1) { + vt = free1; + free1 = free1->next; + } + else { + vt = (PTEXT) malloc(sizeof(PTEXT_ST)); + if (!vt) return(NULL); + ptext_max++; + } + ptext_count++; + + /* nearly all parts are 0 [or NULL] */ + ZERO(vt); + /* The offset is to leave room for additional headers */ + vt->start = vt->dat + MAX_PTXT_HDR; + + return(vt); + } + + /* + * ptfree - free a VTEXT structure + * + * VTFREE takes a pointer to a VTEXT structure and adds it to + * the free list for later reuse. + */ + + void ptfree(PTEXT vt) + { + vt->next = free1; + vt->previous = NULL; + free1 = vt; + ptext_count--; + } + + /* + * ptlfree - free a VTEXT structure + * + * VTLFREE takes a pointer to a VTEXT structure frees it and any linked + * VTEXT structures. It is used to free an entrie list of VTEXT + * structures. + */ + + void ptlfree(PTEXT vt) + { + PTEXT nxt; + + while(vt != NULL) { + nxt = vt->next; + ptfree(vt); + vt = nxt; + } + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/rdgram.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/rdgram.h:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/rdgram.h Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,16 ---- + /* + * Copyright (c) 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + */ + + #include + + /* Queuing priorities for datagrams */ + #define RDGRAM_MAX_PRI 32765 /* Maximum user proiority */ + #define RDGRAM_MAX_SPRI 32767 /* Maximum priority for system use */ + #define RDGRAM_MIN_PRI -32765 /* Maximum user proiority */ + #define RDGRAM_MIN_SPRI -32768 /* Maximum priority for system use */ + + int rdgram_priority = 0; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/regex.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/regex.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/regex.c Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,685 ---- + #include + + #ifdef NOREGEX + /* + * These routines are BSD regex(3)/ed(1) compatible regular-expression + * routines written by Ozan S. Yigit, Computer Science, York University. + * Parts of the code that are not needed by Prospero have been removed, + * but most of the accompanying information has been left intact. + * This file is to be included on those operating systems that do not + * support re_comp and re_exec. + */ + + /* + * regex - Regular expression pattern matching + * and replacement + * + * by: Ozan S. Yigit (oz at nexus.yorku.ca) + * Dept. of Computing Services + * York University + * + * These routines are the PUBLIC DOMAIN equivalents + * of regex routines as found in 4.nBSD UN*X, with minor + * extensions. + * + * Modification history: + * + * $Log: regex.c,v $ + * Revision 1.1 2004/10/05 18:19:58 lattner + * New "Benchmark". Of course running it just prints usage info, but whatever. + * + * Revision 1.3 89/04/01 14:18:09 oz + * Change all references to a dfa: this is actually an nfa. + * + * Revision 1.2 88/08/28 15:36:04 oz + * Use a complement bitmap to represent NCL. + * This removes the need to have seperate + * code in the pmatch case block - it is + * just CCL code now. + * + * Use the actual CCL code in the CLO + * section of pmatch. No need for a recursive + * pmatch call. + * + * Use a bitmap table to set char bits in an + * 8-bit chunk. + * + * Routines: + * re_comp: compile a regular expression into + * a NFA. + * + * char *re_comp(s) + * char *s; + * + * re_exec: execute the NFA to match a pattern. + * + * int re_exec(s) + * char *s; + * + * Regular Expressions: + * + * [1] char matches itself, unless it is a special + * character (metachar): . \ [ ] * + ^ $ + * + * [2] . matches any character. + * + * [3] \ matches the character following it, except + * when followed by a left or right round bracket, + * a digit 1 to 9 or a left or right angle bracket. + * (see [7], [8] and [9]) + * It is used as an escape character for all + * other meta-characters, and itself. When used + * in a set ([4]), it is treated as an ordinary + * character. + * + * [4] [set] matches one of the characters in the set. + * If the first character in the set is "^", + * it matches a character NOT in the set, i.e. + * complements the set. A shorthand S-E is + * used to specify a set of characters S upto + * E, inclusive. The special characters "]" and + * "-" have no special meaning if they appear + * as the first chars in the set. + * examples: match: + * + * [a-z] any lowercase alpha + * + * [^]-] any char except ] and - + * + * [^A-Z] any char except uppercase + * alpha + * + * [a-zA-Z] any alpha + * + * [5] * any regular expression form [1] to [4], followed by + * closure char (*) matches zero or more matches of + * that form. + * + * [6] + same as [5], except it matches one or more. + * + * [7] a regular expression in the form [1] to [10], enclosed + * as \(form\) matches what form matches. The enclosure + * creates a set of tags, used for [8] and for + * pattern substution. The tagged forms are numbered + * starting from 1. + * + * [8] a \ followed by a digit 1 to 9 matches whatever a + * previously tagged regular expression ([7]) matched. + * + * [9] \< a regular expression starting with a \< construct + * \> and/or ending with a \> construct, restricts the + * pattern matching to the beginning of a word, and/or + * the end of a word. A word is defined to be a character + * string beginning and/or ending with the characters + * A-Z a-z 0-9 and _. It must also be preceded and/or + * followed by any character outside those mentioned. + * + * [10] a composite regular expression xy where x and y + * are in the form [1] to [10] matches the longest + * match of x followed by a match for y. + * + * [11] ^ a regular expression starting with a ^ character + * $ and/or ending with a $ character, restricts the + * pattern matching to the beginning of the line, + * or the end of line. [anchors] Elsewhere in the + * pattern, ^ and $ are treated as ordinary characters. + * + * + * Acknowledgements: + * + * HCR's Hugh Redelmeier has been most helpful in various + * stages of development. He convinced me to include BOW + * and EOW constructs, originally invented by Rob Pike at + * the University of Toronto. + * + * References: + * Software tools Kernighan & Plauger + * Software tools in Pascal Kernighan & Plauger + * Grep [rsx-11 C dist] David Conroy + * ed - text editor Un*x Programmer's Manual + * Advanced editing on Un*x B. W. Kernighan + * regexp routines Henry Spencer + * + * Notes: + * + * This implementation uses a bit-set representation for character + * classes for speed and compactness. Each character is represented + * by one bit in a 128-bit block. Thus, CCL always takes a + * constant 16 bytes in the internal nfa, and re_exec does a single + * bit comparison to locate the character in the set. + * + * Examples: + * + * pattern: foo*.* + * compile: CHR f CHR o CLO CHR o END CLO ANY END END + * matches: fo foo fooo foobar fobar foxx ... + * + * pattern: fo[ob]a[rz] + * compile: CHR f CHR o CCL bitset CHR a CCL bitset END + * matches: fobar fooar fobaz fooaz + * + * pattern: foo\\+ + * compile: CHR f CHR o CHR o CHR \ CLO CHR \ END END + * matches: foo\ foo\\ foo\\\ ... + * + * pattern: \(foo\)[1-3]\1 (same as foo[1-3]foo) + * compile: BOT 1 CHR f CHR o CHR o EOT 1 CCL bitset REF 1 END + * matches: foo1foo foo2foo foo3foo + * + * pattern: \(fo.*\)-\1 + * compile: BOT 1 CHR f CHR o CLO ANY END EOT 1 CHR - REF 1 END + * matches: foo-foo fo-fo fob-fob foobar-foobar ... + * + */ + + #define MAXNFA 1024 + #define MAXTAG 10 + + #define OKP 1 + #define NOP 0 + + #define CHR 1 + #define ANY 2 + #define CCL 3 + #define BOL 4 + #define EOL 5 + #define BOT 6 + #define EOT 7 + #define BOW 8 + #define EOW 9 + #define REF 10 + #define CLO 11 + + #define END 0 + + /* + * The following defines are not meant + * to be changeable. They are for readability + * only. + * + */ + #define MAXCHR 128 + #define CHRBIT 8 + #define BITBLK MAXCHR/CHRBIT + #define BLKIND 0170 + #define BITIND 07 + + #define ASCIIB 0177 + + typedef /*unsigned*/ char CHAR; + + static int tagstk[MAXTAG]; /* subpat tag stack..*/ + static CHAR nfa[MAXNFA]; /* automaton.. */ + static int sta = NOP; /* status of lastpat */ + + static CHAR bittab[BITBLK]; /* bit table for CCL */ + /* pre-set bits... */ + static CHAR bitarr[] = {1,2,4,8,16,32,64,128}; + + static int internal_error; + + static void chset(register CHAR c) + { + bittab[((c) & BLKIND) >> 3] |= bitarr[(c) & BITIND]; + } + + #define badpat(x) return (*nfa = END, x) + #define store(x) *mp++ = x + + char *re_comp(char *pat) + { + register char *p; /* pattern pointer */ + register CHAR *mp = nfa; /* nfa pointer */ + register CHAR *lp; /* saved pointer.. */ + register CHAR *sp = nfa; /* another one.. */ + + register int tagi = 0; /* tag stack index */ + register int tagc = 1; /* actual tag count */ + + register int n; + register CHAR mask; /* xor mask -CCL/NCL */ + int c1, c2; + + if (!pat || !*pat) + if (sta) + return 0; + else + badpat("No previous regular expression"); + sta = NOP; + + for (p = pat; *p; p++) { + lp = mp; + switch(*p) { + + case '.': /* match any char.. */ + store(ANY); + break; + + case '^': /* match beginning.. */ + if (p == pat) + store(BOL); + else { + store(CHR); + store(*p); + } + break; + + case '$': /* match endofline.. */ + if (!*(p+1)) + store(EOL); + else { + store(CHR); + store(*p); + } + break; + + case '[': /* match char class..*/ + store(CCL); + + if (*++p == '^') { + mask = 0377; + p++; + } + else + mask = 0; + + if (*p == '-') /* real dash */ + chset(*p++); + if (*p == ']') /* real brac */ + chset(*p++); + while (*p && *p != ']') { + if (*p == '-' && *(p+1) && *(p+1) != ']') { + p++; + c1 = *(p-2) + 1; + c2 = *p++; + while (c1 <= c2) + chset(c1++); + } + #ifdef EXTEND + else if (*p == '\\' && *(p+1)) { + p++; + chset(*p++); + } + #endif + else + chset(*p++); + } + if (!*p) + badpat("Missing ]"); + + for (n = 0; n < BITBLK; bittab[n++] = (char) 0) + store(mask ^ bittab[n]); + + break; + + case '*': /* match 0 or more.. */ + case '+': /* match 1 or more.. */ + if (p == pat) + badpat("Empty closure"); + lp = sp; /* previous opcode */ + if (*lp == CLO) /* equivalence.. */ + break; + switch(*lp) { + + case BOL: + case BOT: + case EOT: + case BOW: + case EOW: + case REF: + badpat("Illegal closure"); + default: + break; + } + + if (*p == '+') + for (sp = mp; lp < sp; lp++) + store(*lp); + + store(END); + store(END); + sp = mp; + while (--mp > lp) + *mp = mp[-1]; + store(CLO); + mp = sp; + break; + + case '\\': /* tags, backrefs .. */ + switch(*++p) { + + case '(': + if (tagc < MAXTAG) { + tagstk[++tagi] = tagc; + store(BOT); + store(tagc++); + } + else + badpat("Too many \\(\\) pairs"); + break; + case ')': + if (*sp == BOT) + badpat("Null pattern inside \\(\\)"); + if (tagi > 0) { + store(EOT); + store(tagstk[tagi--]); + } + else + badpat("Unmatched \\)"); + break; + case '<': + store(BOW); + break; + case '>': + if (*sp == BOW) + badpat("Null pattern inside \\<\\>"); + store(EOW); + break; + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + n = *p-'0'; + if (tagi > 0 && tagstk[tagi] == n) + badpat("Cyclical reference"); + if (tagc > n) { + store(REF); + store(n); + } + else + badpat("Undetermined reference"); + break; + #ifdef EXTEND + case 'b': + store(CHR); + store('\b'); + break; + case 'n': + store(CHR); + store('\n'); + break; + case 'f': + store(CHR); + store('\f'); + break; + case 'r': + store(CHR); + store('\r'); + break; + case 't': + store(CHR); + store('\t'); + break; + #endif + default: + store(CHR); + store(*p); + } + break; + + default : /* an ordinary char */ + store(CHR); + store(*p); + break; + } + sp = lp; + } + if (tagi > 0) + badpat("Unmatched \\("); + store(END); + sta = OKP; + return 0; + } + + + static char *bol; + static char *bopat[MAXTAG]; + static char *eopat[MAXTAG]; + char *pmatch(); + + /* + * re_exec: + * execute nfa to find a match. + * + * special cases: (nfa[0]) + * BOL + * Match only once, starting from the + * beginning. + * CHR + * First locate the character without + * calling pmatch, and if found, call + * pmatch for the remaining string. + * END + * re_comp failed, poor luser did not + * check for it. Fail fast. + * + * If a match is found, bopat[0] and eopat[0] are set + * to the beginning and the end of the matched fragment, + * respectively. + * + */ + + int re_exec(register char *lp) + { + register char c; + register char *ep = 0; + register CHAR *ap = nfa; + + bol = lp; + + bopat[0] = 0; + bopat[1] = 0; + bopat[2] = 0; + bopat[3] = 0; + bopat[4] = 0; + bopat[5] = 0; + bopat[6] = 0; + bopat[7] = 0; + bopat[8] = 0; + bopat[9] = 0; + + switch(*ap) { + + case BOL: /* anchored: match from BOL only */ + ep = pmatch(lp,ap); + break; + case CHR: /* ordinary char: locate it fast */ + c = *(ap+1); + while (*lp && *lp != c) + lp++; + if (!*lp) /* if EOS, fail, else fall thru. */ + return 0; + default: /* regular matching all the way. */ + while (*lp) { + if ((ep = pmatch(lp,ap))) + break; + lp++; + } + break; + case END: /* munged automaton. fail always */ + return 0; + } + if (!ep) + return 0; + + if (internal_error) + return -1; + + bopat[0] = lp; + eopat[0] = ep; + return 1; + } + + /* + * pmatch: + * internal routine for the hard part + * + * This code is mostly snarfed from an early + * grep written by David Conroy. The backref and + * tag stuff, and various other mods are by oZ. + * + * special cases: (nfa[n], nfa[n+1]) + * CLO ANY + * We KNOW ".*" will match ANYTHING + * upto the end of line. Thus, go to + * the end of line straight, without + * calling pmatch recursively. As in + * the other closure cases, the remaining + * pattern must be matched by moving + * backwards on the string recursively, + * to find a match for xy (x is ".*" and + * y is the remaining pattern) where + * the match satisfies the LONGEST match + * for x followed by a match for y. + * CLO CHR + * We can again scan the string forward + * for the single char without recursion, + * and at the point of failure, we execute + * the remaining nfa recursively, as + * described above. + * + * At the end of a successful match, bopat[n] and eopat[n] + * are set to the beginning and end of subpatterns matched + * by tagged expressions (n = 1 to 9). + * + */ + + /* + * character classification table for word boundary + * operators BOW and EOW. the reason for not using + * ctype macros is that we can let the user add into + * our own table. see re_modw. This table is not in + * the bitset form, since we may wish to extend it + * in the future for other character classifications. + * + * TRUE for 0-9 A-Z a-z _ + */ + static char chrtyp[MAXCHR] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, + 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 0, 0, 0, 0, 0 + }; + + #define inascii(x) (0177&(x)) + #define iswordc(x) chrtyp[inascii(x)] + #define isinset(x,y) ((x)[((y)&BLKIND)>>3] & bitarr[(y)&BITIND]) + + /* + * skip values for CLO XXX to skip past the closure + * + */ + + #define ANYSKIP 2 /* [CLO] ANY END ... */ + #define CHRSKIP 3 /* [CLO] CHR chr END ... */ + #define CCLSKIP 18 /* [CLO] CCL 16bytes END ... */ + + static char *pmatch(register char *lp,register CHAR *ap) + { + register int op, c, n; + register char *e; /* extra pointer for CLO */ + register char *bp; /* beginning of subpat.. */ + register char *ep; /* ending of subpat.. */ + char *are; /* to save the line ptr. */ + + while ((op = *ap++) != END) + switch(op) { + + case CHR: + if (*lp++ != *ap++) + return 0; + break; + case ANY: + if (!*lp++) + return 0; + break; + case CCL: + c = *lp++; + if (!isinset(ap,c)) + return 0; + ap += BITBLK; + break; + case BOL: + if (lp != bol) + return 0; + break; + case EOL: + if (*lp) + return 0; + break; + case BOT: + bopat[*ap++] = lp; + break; + case EOT: + eopat[*ap++] = lp; + break; + case BOW: + if (lp!=bol && iswordc(lp[-1]) || !iswordc(*lp)) + return 0; + break; + case EOW: + if (lp==bol || !iswordc(lp[-1]) || iswordc(*lp)) + return 0; + break; + case REF: + n = *ap++; + bp = bopat[n]; + ep = eopat[n]; + while (bp < ep) + if (*bp++ != *lp++) + return 0; + break; + case CLO: + are = lp; + switch(*ap) { + + case ANY: + while (*lp) + lp++; + n = ANYSKIP; + break; + case CHR: + c = *(ap+1); + while (*lp && c == *lp) + lp++; + n = CHRSKIP; + break; + case CCL: + while ((c = *lp) && isinset(ap+1,c)) + lp++; + n = CCLSKIP; + break; + default: + internal_error++; + return 0; + } + + ap += n; + + while (lp >= are) { + if (e = pmatch(lp, ap)) + return e; + --lp; + } + return 0; + default: + internal_error++; + return 0; + } + return lp; + } + #endif /* Need regex libraries? Compile to nothing if not. */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/regex.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/regex.h:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/regex.h Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,23 ---- + /* + * regex.h : External defs for Ozan Yigit's regex functions, for systems + * that don't have them builtin. See regex.c for copyright and other + * details. + * + * Note that this file can be included even if we're linking against the + * system routines, since the interface is (deliberately) identical. + * + * George Ferguson, ferguson at cs.rochester.edu, 11 Sep 1991. + */ + + #if defined(AUX) || defined(USG) + /* Let them use ours if they wish. */ + # ifndef NOREGEX + extern char *regcmp(); + extern char *regex(); + #define re_comp regcmp + #define re_exec regex + # endif + #else + extern char *re_comp(); + extern int re_exec(); + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/stcopy.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/stcopy.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/stcopy.c Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,103 ---- + /* + * Copyright (c) 1989, 1990, 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + * + * v1.2.1 - 11/19/91 (mmt) - added MSDOS & OS2 stuff + * v1.2.0 - 09/17/91 (bpk) - added BULL & USG stuff, thanks to Jim Sillas + */ + + #include + #include + #include + #include + + #ifdef NEED_STRING_H + # include + #else + # include + #endif + + #if defined(MSDOS) + # include + #endif + + char *stcopyr(); + + int string_count = 0; + int string_max = 0; + + /* + * stcopy - allocate space for and copy a string + * + * STCOPY takes a string as an argument, allocates space for + * a copy of the string, copies the string to the allocated space, + * and returns a pointer to the copy. + */ + + char *stcopy(char *st) + { + if (!st) return(NULL); + if (string_max < ++string_count) string_max = string_count; + + return strcpy((char *)malloc(strlen(st) + 1), st); + } + + /* + * stcopyr - copy a string allocating space if necessary + * + * STCOPYR takes a string, S, as an argument, and a pointer to a second + * string, R, which is to be replaced by S. If R is long enough to + * hold S, S is copied. Otherwise, new space is allocated, and R is + * freed. S is then copied to the newly allocated space. If S is + * NULL, then R is freed and NULL is returned. + * + * In any event, STCOPYR returns a pointer to the new copy of S, + * or a NULL pointer. + */ + + char *stcopyr(char *s,char *r) + { + int sl; + + if(!s && r) { + free(r); + string_count--; + return(NULL); + } + else if (!s) return(NULL); + + sl = strlen(s) + 1; + + if(r) { + if ((strlen(r) + 1) < sl) { + free(r); + r = (char *) malloc(sl); + } + } + else { + r = (char *) malloc(sl); + string_count++; + if(string_max < string_count) string_max = string_count; + } + + return strcpy(r,s); + } + + /* + * stfree - free space allocated by stcopy or stalloc + * + * STFREE takes a string that was returned by stcopy or stalloc + * and frees the space that was allocated for the string. + */ + + void stfree(char *st) + { + if(st) { + free(st); + string_count--; + } + } + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/support.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/support.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/support.c Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,792 ---- + /* + * Copyright (c) 1989, 1990, 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + * + * v1.2.2 - 11/19/91 (mmt) - added MSDOS & OS2 stuff + * v1.2.1 - 09/23/91 (gf) - made it use regex.h---much nicer + * v1.2.0 - 09/17/91 (bpk) - added BULL & USG stuff, thanks to Jim Sillas + * v1.1.1 - 08/30/91 (bpk) - added VMS support; cast index() + */ + + /* + * Miscellaneous routines pulled from ~beta/lib/pfs and ~beta/lib/filters + */ + + #include + #include + + #include + + #ifdef VMS + # ifdef WOLLONGONG + # include "twg$tcp:[netdist.include]netdb.h" + # else /* not Wollongong */ + # ifdef UCX + # include netdb + # else /* Multinet */ + # include "multinet_root:[multinet.include]netdb.h" + # endif + # endif + # include + #else /* not VMS */ + # include + # include + # ifdef NEED_STRING_H + # include + # else + # include + # endif + # ifndef CUTCP + # include + # endif + # if !defined(MSDOS) || defined(OS2) + # include + # include + # endif + #endif /* VMS */ + + #include + #include + #include + #include + #include + + #include "regex.h" + + int pfs_enable = PMAP_ATSIGN; + + #ifndef FALSE + # define TRUE 1 + # define FALSE 0 + #endif + + extern int vl_comp(VLINK vl1,VLINK vl2); + extern int vl_equal(VLINK vl1,VLINK vl2); + + /* + * wcmatch - Match string s against template containing widlcards + * + * WCMATCH takes a string and a template, and returns + * true if the string matches the template, and + * FALSE otherwise. + * + * ARGS: s - string to be tested + * template - Template containing optional wildcards + * + * RETURNS: TRUE (non-zero) on match. FALSE (0) otherwise. + * + * NOTE: If template is NULL, will return TRUE. + * + */ + + int wcmatch(char *s,char *template) + { + char temp[200]; + char *p = temp; + + if(!template) return(TRUE); + *p++ = '^'; + + while(*template) { + if(*template == '*') {*(p++)='.'; *(p++) = *(template++);} + else if(*template == '?') {*(p++)='.';template++;} + else if(*template == '.') {*(p++)='\\';*(p++)='.';template++;} + else if(*template == '[') {*(p++)='\\';*(p++)='[';template++;} + else if(*template == '$') {*(p++)='\\';*(p++)='$';template++;} + else if(*template == '^') {*(p++)='\\';*(p++)='^';template++;} + else if(*template == '\\') {*(p++)='\\';*(p++)='\\';template++;} + else *(p++) = *(template++); + } + + *p++ = '$'; + *p++ = '\0'; + + if(re_comp(temp)) return(FALSE); + + #ifdef AUX + if (re_exec(s) == (char *)NULL) + return 0; + return 1; + #else + return(re_exec(s)); + #endif + } + + /* + * ul_insert - Insert a union link at the right location + * + * UL_INSERT takes a directory and a union link to be added + * to a the list of union links in the directory. It then + * inserts the union link in the right spot in the linked + * list of union links associated with that directory. + * + * If an identical link already exists, then the link which + * would be evaluated earlier (closer to the front of the list) + * wins and the other one is freed. If this happens, an error + * will also be returned. + * + * ARGS: ul - link to be inserted + * vd - directory to get link + * p - vl that this link will apper after + * NULL - This vl will go at end of list + * vd - This vl will go at head of list + * + * RETURNS: Success, or UL_INSERT_ALREADY_THERE or UL_INSERT_SUPERSEDING + */ + + int ul_insert(VLINK ul,VDIR1 vd,VLINK p) + { + VLINK current; + + /* This is the first ul in the directory */ + if(vd->ulinks == NULL) { + vd->ulinks = ul; + ul->previous = NULL; + ul->next = NULL; + return(PSUCCESS); + } + + /* This ul will go at the head of the list */ + if(p == (VLINK) vd) { + ul->next = vd->ulinks; + ul->next->previous = ul; + vd->ulinks = ul; + ul->previous = NULL; + } + /* Otherwise, decide if it must be inserted at all */ + /* If an identical link appears before the position */ + /* at which the new one is to be inserted, we can */ + /* return without inserting it */ + else { + current = vd->ulinks; + + while(current) { + /* p == NULL means we insert after last link */ + if(!p && (current->next == NULL)) + p = current; + + if(vl_comp(current,ul) == 0) { + vlfree(ul); + return(UL_INSERT_ALREADY_THERE); + } + + if(current == p) break; + current = current->next; + } + + /* If current is null, p was not found */ + if(current == NULL) + return(UL_INSERT_POS_NOTFOUND); + + /* Insert ul */ + ul->next = p->next; + p->next = ul; + ul->previous = p; + if(ul->next) ul->next->previous = ul; + } + + /* Check for identical links after ul */ + current = ul->next; + + while(current) { + if(vl_comp(current,ul) == 0) { + current->previous->next = current->next; + if(current->next) + current->next->previous = current->previous; + vlfree(current); + return(UL_INSERT_SUPERSEDING); + } + current = current->next; + } + + return(PSUCCESS); + } + + /* + * vl_insert - Insert a directory link at the right location + * + * VL_INSERT takes a directory and a link to be added to a + * directory and inserts it in the linked list of links for + * that directory. + * + * If a link already exists with the same name, and if the + * information associated with the new link matches that in + * the existing link, an error is returned. If the information + * associated with the new link is different, but the magic numbers + * match, then the new link will be added as a replica of the + * existing link. If the magic numbers do not match, the new + * link will only be added to the list of "replicas" if the + * allow_conflict flag has been set. + * + * If the link is not added, an error is returned and the link + * is freed. Ordering for the list of links is by the link name. + * + * If vl is a union link, then VL_INSERT calls ul_insert with an + * added argument indicating the link is to be included at the + * end of the union link list. + * + * ARGS: vl - Link to be inserted, vd - directory to get link + * allow_conflict - insert links with conflicting names + * + * RETURNS: Success, or VL_INSERT_ALREADY_THERE + */ + + int vl_insert(VLINK vl,VDIR1 vd,int allow_conflict) + { + VLINK current; /* To step through list */ + VLINK crep; /* To step through list of replicas */ + int retval; /* Temp for checking returned values */ + + /* This can also be used to insert union links at end of list */ + if(vl->linktype == 'U') return(ul_insert(vl,vd,NULL)); + + /* If this is the first link in the directory */ + if(vd->links == NULL) { + vd->links = vl; + vl->previous = NULL; + vl->next = NULL; + vd->lastlink = vl; + return(PSUCCESS); + } + + /* If no sorting is to be done, just insert at end of list */ + if(allow_conflict == VLI_NOSORT) { + vd->lastlink->next = vl; + vl->previous = vd->lastlink; + vl->next = NULL; + vd->lastlink = vl; + return(PSUCCESS); + } + + /* If it is to be inserted at start of list */ + if(vl_comp(vl,vd->links) < 0) { + vl->next = vd->links; + vl->previous = NULL; + vl->next->previous = vl; + vd->links = vl; + return(PSUCCESS); + } + + current = vd->links; + + /* Otherwise, we must find the right spot to insert it */ + while((retval = vl_comp(vl,current)) > 0) { + if(!current->next) { + /* insert at end */ + vl->previous = current; + vl->next = NULL; + current->next = vl; + vd->lastlink = vl; + return(PSUCCESS); + } + current = current->next; + } + + /* If we found an equivilant entry already in list */ + if(!retval) { + if(vl_equal(vl,current)) { + vlfree(vl); + return(VL_INSERT_ALREADY_THERE); + } + if((allow_conflict == VLI_NOCONFLICT) && + ((vl->f_magic_no != current->f_magic_no) || + (vl->f_magic_no==0))) + return(VL_INSERT_CONFLICT); + /* Insert the link into the list of "replicas" */ + /* If magic is 0, then create a pseudo magic number */ + if(vl->f_magic_no == 0) vl->f_magic_no = -1; + crep = current->replicas; + if(!crep) { + current->replicas = vl; + vl->next = NULL; + vl->previous = NULL; + } + else { + while(crep->next) { + /* If magic was 0, then we need a unique magic number */ + if((crep->f_magic_no < 0) && (vl->f_magic_no < 1)) + (vl->f_magic_no)--; + crep = crep->next; + } + /* If magic was 0, then we need a unique magic number */ + if((crep->f_magic_no < 0) && (vl->f_magic_no < 1)) + (vl->f_magic_no)--; + crep->next = vl; + vl->previous = crep; + vl->next = NULL; + } + return(PSUCCESS); + } + + /* We found the spot where vl is to be inserted */ + vl->next = current; + vl->previous = current->previous; + current->previous = vl; + vl->previous->next = vl; + return(PSUCCESS); + } + + /* + * nlsindex - Find first instance of string 2 in string 1 following newline + * + * NLSINDEX scans string 1 for the first instance of string + * 2 that immediately follows a newline. If found, NLSINDEX + * returns a pointer to the first character of that instance. + * If no instance is found, NLSINDEX returns NULL (0). + * + * NOTE: This function is only useful for searching strings that + * consist of multiple lines. s1 is assumed to be preceeded + * by a newline. Thus, if s2 is at the start of s1, it will + * be found. + * ARGS: s1 - string to be searched + * s2 - string to be found + * RETURNS: First instance of s2 in s1, or NULL (0) if not found + */ + + char *nlsindex(char *s1,char *s2) + { + register int s2len = strlen(s2); + char *curline = s1; /* Pointer to start of current line */ + + /* In case s2 appears at start of s1 */ + if(strncmp(curline,s2,s2len) == 0) + return(curline); + + /* Check remaining lines of s1 */ + while((curline = strchr(curline,(int) '\n')) != NULL) { + curline++; + if(strncmp(curline,s2,s2len) == 0) + return(curline); + } + + /* We didn't find it */ + return(NULL); + } + + /* + * month_sname - Return a month name from it's number + * + * MONTH_SNAME takes a number in the range 0 + * to 12 and returns a pointer to a string + * representing the three letter abbreviation + * for that month. If the argument is out of + * range, MONTH_SNAME returns a pointer to "Unk". + * + * ARGS: n - Number of the month + * RETURNS: Abbreviation for selected month + */ + + char *month_sname(int n) + { + static char *name[] = { "Unk", + "Jan","Feb","Mar","Apr","May","Jun", + "Jul","Aug","Sep","Oct","Nov","Dec" + }; + return((n < 1 || n > 12) ? name[0] : name[n]); + } + + /* + * sindex - Find first instance of string 2 in string 1 + * + * SINDEX scans string 1 for the first instance of string + * 2. If found, SINDEX returns a pointer to the first + * character of that instance. If no instance is found, + * SINDEX returns NULL (0). + * + * ARGS: s1 - string to be searched + * s2 - string to be found + * RETURNS: First instance of s2 in s1, or NULL (0) if not found + */ + + char *sindex(char *s1,char *s2) + { + register int s2len = strlen(s2); + char *s = s1; /* Temp pointer to string */ + + /* Check for first character of s2 */ + while((s = strchr(s,(int) *s2)) != NULL) { + if(strncmp(s,s2,s2len) == 0) + return(s); + s++; + } + + /* We didn't find it */ + return(NULL); + } + + int scan_error(char *erst) + { + *p_err_string = '\0'; + + if(strncmp(erst,"NOT-A-DIRECTORY",15) == 0) + return(DIRSRV_NOT_DIRECTORY); + + if(strncmp(erst,"UNIMPLEMENTED",13) == 0) { + perrno = DIRSRV_UNIMPLEMENTED; + sscanf(erst+13,"%*[^\n \t\r]%*[ \t]%[^\n]",p_err_string); + return(perrno); + } + + if(strncmp(erst,"WARNING ",8) == 0) { + erst += 8; + *p_warn_string = '\0'; + sscanf(erst,"%*[^\n \t\r]%*[ \t]%[^\n]",p_warn_string); + /* Return values for warnings are negative */ + if(strncmp(erst,"OUT-OF-DATE",11) == 0) { + pwarn = PWARN_OUT_OF_DATE; + return(PSUCCESS); + } + if(strncmp(erst,"MESSAGE",7) == 0) { + pwarn = PWARN_MSG_FROM_SERVER; + return(PSUCCESS); + } + pwarn = PWARNING; + sscanf(erst,"%[^\n]",p_warn_string); + return(PSUCCESS); + } + else if(strncmp(erst,"ERROR",5) == 0) { + if(*(erst+5)) sscanf(erst+6,"%[^\n]",p_err_string); + perrno = DIRSRV_ERROR; + return(perrno); + } + /* The rest start with "FAILURE" */ + else if(strncmp(erst,"FAILURE",7) != 0) { + /* Unrecognized - Give warning, but return PSUCCESS */ + if(pwarn == 0) { + *p_warn_string = '\0'; + pwarn = PWARN_UNRECOGNIZED_RESP; + sscanf(erst,"%[^\n]",p_warn_string); + } + return(PSUCCESS); + } + + if(strncmp(erst,"FAILURE ",8) != 0) { + perrno = PFAILURE; + return(perrno); + } + erst += 8; + + sscanf(erst,"%*[^\n \t\r]%*[ \t]%[^\n]",p_err_string); + + /* Still to add */ + /* DIRSRV_AUTHENT_REQ 242 */ + /* DIRSRV_BAD_VERS 245 */ + + if(strncmp(erst,"NOT-FOUND",9) == 0) + perrno = DIRSRV_NOT_FOUND; + else if(strncmp(erst,"NOT-AUTHORIZED",13) == 0) + perrno = DIRSRV_NOT_AUTHORIZED; + else if(strncmp(erst,"ALREADY-EXISTS",14) == 0) + perrno = DIRSRV_ALREADY_EXISTS; + else if(strncmp(erst,"NAME-CONFLICT",13) == 0) + perrno = DIRSRV_NAME_CONFLICT; + else if(strncmp(erst,"SERVER-FAILED",13) == 0) + perrno = DIRSRV_SERVER_FAILED; + /* Use it whether it starts with FAILURE or not */ + else if(strncmp(erst,"NOT-A-DIRECTORY",15) == 0) + perrno = DIRSRV_NOT_DIRECTORY; + else perrno = PFAILURE; + + return(perrno); + } + + PATTRIB parse_attribute(char *line) + { + char l_precedence[MAX_DIR_LINESIZE]; + char l_name[MAX_DIR_LINESIZE]; + char l_type[MAX_DIR_LINESIZE]; + char l_value[MAX_DIR_LINESIZE]; + PATTRIB at; + int tmp; + + tmp = sscanf(line,"OBJECT-INFO %s %s %[^\n]", l_name, l_type, l_value); + + if(tmp < 3) { + tmp = sscanf(line,"LINK-INFO %s %s %s %[^\n]", l_precedence, + l_name, l_type, l_value); + if(tmp < 4) { + perrno = DIRSRV_BAD_FORMAT; + return(NULL); + } + } + + at = atalloc(); + + if(tmp == 4) { + if(strcmp(l_precedence,"CACHED") == 0) + at->precedence = ATR_PREC_CACHED; + else if(strcmp(l_precedence,"LINK") == 0) + at->precedence = ATR_PREC_LINK; + else if(strcmp(l_precedence,"REPLACEMENT") == 0) + at->precedence = ATR_PREC_REPLACE; + else if(strcmp(l_precedence,"ADDITIONAL") == 0) + at->precedence = ATR_PREC_ADD; + } + + at->aname = stcopy(l_name); + at->avtype = stcopy(l_type); + if(strcmp(l_type,"ASCII") == 0) + at->value.ascii = stcopy(l_value); + else if(strcmp(l_type,"LINK") == 0) { + char ftype[MAX_DIR_LINESIZE]; + char lname[MAX_DIR_LINESIZE]; + char htype[MAX_DIR_LINESIZE]; + char host[MAX_DIR_LINESIZE]; + char ntype[MAX_DIR_LINESIZE]; + char fname[MAX_DIR_LINESIZE]; + VLINK al; + + al = vlalloc(); + at->value.link = al; + + tmp = sscanf(l_value,"%c %s %s %s %s %s %s %d %d", + &(al->linktype), + ftype,lname,htype,host,ntype,fname, + &(al->version), + &(al->f_magic_no)); + if(tmp == 9) { + al->type = stcopyr(ftype,al->type); + al->name = stcopyr(unquote(lname),al->name); + al->hosttype = stcopyr(htype,al->hosttype); + al->host = stcopyr(host,al->host); + al->nametype = stcopyr(ntype,al->nametype); + al->filename = stcopyr(fname,al->filename); + } + else { + perrno = DIRSRV_BAD_FORMAT; + return(NULL); + } + + } + + return(at); + } + + /* + * nxtline - Find the next line in the string + * + * NXTLINE takes a string and returns a pointer to + * the character immediately following the next newline. + * + * ARGS: s - string to be searched + * + * RETURNS: Next line or NULL (0) on failure + */ + + char *nxtline(char *s) + /* String to be searched */ + { + s = strchr(s,(int) '\n'); + if(s) return(++s); + else return(NULL); + } + + + /* + * unquote - unquote string if necessary + * + * UNQUOTE takes a string and unquotes it if it has been quoted. + * + * ARGS: s - string to be unquoted + * + * RETURNS: The original string. If the string has been quoted, then the + * result appears in static storage, and must be copied if + * it is to last beyond the next call to quote. + * + */ + + char *unquote(char *s) + /* String to be quoted */ + { + static char unquoted[200]; + char *c = unquoted; + + if(*s != '\'') return(s); + + s++; + + /* This should really treat a quote followed by other */ + /* than a quote or a null as an error */ + while(*s) { + if(*s == '\'') s++; + if(*s) *c++ = *s++; + } + + *c++ = '\0'; + + return(unquoted); + } + + #if defined(DEBUG) && defined(STRSPN) + /* needed for -D option parsing */ + /* + * strspn - Count initial characters from chrs in s + * + * STRSPN counts the occurances of chacters from chrs + * in the string s preceeding the first occurance of + * a character not in s. + * + * ARGS: s - string to be checked + * chrs - string of characters we are looking for + * + * RETURNS: Count of initial characters from chrs in s + */ + + int strspn(char *s,char *chrs) + { + char *cp; /* Pointer to the current character in chrs */ + int count; /* Count of characters seen so far */ + + count = 0; + + while(*s) { + for(cp = chrs;*cp;cp++) + if(*cp == *s) { + s++; + count++; + goto done; + } + return(count); + done: + ; + } + return(count); + } + #endif + + #ifdef CUTCP + + char *inet_ntoa(struct in_addr in) + { + static char buff[36]; + + unsigned char *c = (char *) &in.address; + sprintf(buff,"%d.%d.%d.%d",*c,*(c+1),*(c+2),*(c+3)); + return(buff); + } + + long inet_addr(char *cp) + { + long value = 0; + unsigned v1,v2,v3,v4; + + v1 = v2 = v3 = v4 = 0xff; + sscanf(cp,"%d.%d.%d.%d",&v1,&v2,&v3,&v4); + value = (v1 << 24) | (v2 << 16) | (v3 << 8) | v4; + return(value); + } + + struct hostent *gethostbyname(char *name) + { + struct machinfo *mp; + int mnum; + unsigned long now; + static struct hostent ht; + extern int pfs_debug; + + mp = Shostlook(name); + if(!mp || (!mp->hostip[0])) { /* DNS lookup */ + #ifdef DEBUG + if (pfs_debug) + fprintf(stderr, "Domain name lookup of %s\n", name); + #endif + mnum = Sdomain(name); /* start a DNS lookup */ + now = time(NULL) + NS_TIMEOUT; + while(now > time(NULL)) { + int i, class, dat; + + Stask(); + i = Sgetevent(USERCLASS, &class, &dat); + if(i == DOMOK) { /* domain lookup ok */ + mp = Slooknum(mnum); + #ifdef DEBUG + if (pfs_debug) + fprintf(stderr, "Domain name lookup of %s Completed OK\n", name); + #endif + break; + } + } + if(!mp) { /* get here if timeout */ + #ifdef DEBUG + if (pfs_debug) + fprintf(stderr, "Domain name lookup of %s Failed\n", name); + #endif + return(NULL); + } + } + ht.h_addr = *((unsigned long *) mp->hostip); + ht.h_length = 4; + ht.h_addrtype = AF_INET; + return(&ht); + + } + #endif /* CUTCP */ + + #ifdef GETENV + /* + * Copyright (c) 1987 Regents of the University of California. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that: (1) source distributions retain this entire copyright + * notice and comment, and (2) distributions including binaries display + * the following acknowledgement: ``This product includes software + * developed by the University of California, Berkeley and its contributors'' + * in the documentation or other materials provided with the distribution + * and in all advertising materials mentioning features or use of this + * software. Neither the name of the University nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + + #if defined(LIBC_SCCS) && !defined(lint) + static char sccsid[] = "@(#)getenv.c 5.7 (Berkeley) 6/1/90"; + #endif /* LIBC_SCCS and not lint */ + + #include + #include + + /* + * getenv -- + * Returns ptr to value associated with name, if any, else NULL. + */ + + char *getenv(char *name) + { + int offset; + char *_findenv(); + + return(_findenv(name, &offset)); + } + + /* + * _findenv -- + * Returns pointer to value associated with name, if any, else NULL. + * Sets offset to be the offset of the name/value combination in the + * environmental array, for use by setenv(3) and unsetenv(3). + * Explicitly removes '=' in argument name. + * + * This routine *should* be a static; don't use it. + */ + + char * _findenv(register char *name,int *offset) + { + extern char **environ; + register int len; + register char **P, *C; + + for (C = name, len = 0; *C && *C != '='; ++C, ++len); + for (P = environ; *P; ++P) + if (!strncmp(*P, name, len)) + if (*(C = *P + len) == '=') { + *offset = P - environ; + return(++C); + } + return(NULL); + } + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/vl_comp.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/vl_comp.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/vl_comp.c Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,68 ---- + /* + * Copyright (c) 1989, 1990, 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + */ + + #include + #include + + /* + * vl_comp - compare the names of two virtual links + * + * VL_COMP compares the names of two links. It returns + * 0 if they are equal, negative if vl1 < vl2, and positive if + * vl1 > vl2. + * + * ARGS: vl1,vl2 - Virtual links to be compared + * + * RETURNS: 0 if equal, + is vl1 > vl2, - if vl1 < vl2 + * + * NOTES: Order of significance is as follows. Existence, + * name. If names do not exist, then hosttype, host, + * native filenametype, native filename. The only time + * the name will not exist if if the link is a union link. + */ + + int vl_comp(VLINK vl1,VLINK vl2) + { + int retval; + + if(vl1->name && !vl2->name) return(1); + if(!vl1->name && vl2->name) return(-1); + if(vl1->name && vl2->name && (*(vl1->name) || *(vl2->name))) + return(strcmp(vl1->name,vl2->name)); + + retval = strcmp(vl1->hosttype,vl2->hosttype); + if(!retval) retval = strcmp(vl1->host,vl2->host); + if(!retval) retval = strcmp(vl1->nametype,vl2->nametype); + if(!retval) retval = strcmp(vl1->filename,vl2->filename); + return(retval); + } + + /* + * vl_equal - compare the values of two virtual links + * + * VL_EQUAL compares the values of two links. It returns + * 1 if all important fields are the same, and 0 otherwise. + * + * ARGS: vl1,vl2 - Virtual links to be compared + * + * RETURNS: 1 if equal, 0 if not equal + * + */ + + int vl_equal(VLINK vl1,VLINK vl2) + { + return strcmp(vl1->name, vl2->name) == 0 && + vl1->linktype == vl2->linktype && + strcmp(vl1->type, vl2->type) == 0 && + strcmp(vl1->hosttype, vl2->hosttype) == 0 && + strcmp(vl1->host, vl2->host) == 0 && + strcmp(vl1->nametype, vl2->nametype) == 0 && + strcmp(vl1->filename, vl2->filename) == 0 && + vl1->version == vl2->version && + vl1->f_magic_no == vl2->f_magic_no ; + + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/vlalloc.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/vlalloc.c:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/vlalloc.c Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,108 ---- + /* + * Copyright (c) 1989, 1990, 1991 by the University of Washington + * + * For copying and distribution information, please see the file + * . + */ + + #include + #include + #include + + #include + #include + + static VLINK lfree = NULL; + int vlink_count = 0; + int vlink_max = 0; + + extern void bzero(char *b,int length); + + /* + * vlalloc - allocate and initialize vlink structure + * + * VLALLOC returns a pointer to an initialized structure of type + * VLINK. If it is unable to allocate such a structure, it + * returns NULL. + */ + VLINK vlalloc(void) + { + VLINK vl; + if(lfree) { + vl = lfree; + lfree = lfree->next; + } + else { + vl = (VLINK) malloc(sizeof(VLINK_ST)); + if (!vl) return(NULL); + vlink_max++; + } + + vlink_count++; + + /* Initialize and fill in default values */ + /* Since all but four are set to a zero-value, + why not just wipe it clean? */ + ZERO(vl); + + vl->linktype = 'L'; + vl->type = stcopy("FILE"); + vl->hosttype = stcopy("INTERNET-D"); + vl->nametype = stcopy("ASCII"); + + return(vl); + } + + /* + * vlfree - free a VLINK structure + * + * VLFREE takes a pointer to a VLINK structure and adds it to + * the free list for later reuse. + */ + + void vlfree(VLINK vl) + { + extern int string_count; + + if(vl->dontfree) return; + /* many of these don't need to call stfree(); since a check + for pointer validity's already done before even calling + it, we can just call free() here then do one big decrement + of string_count at the end. */ + if(vl->name) free(vl->name); + stfree(vl->type); + if(vl->replicas) vllfree(vl->replicas); + stfree(vl->hosttype); + if(vl->host) free(vl->host); + stfree(vl->nametype); + if(vl->filename) free(vl->filename); + if(vl->args) free(vl->args); + if(vl->lattrib) atlfree(vl->lattrib); + /* No allocation routines for f_info yet */ + vl->f_info = NULL; + vl->next = lfree; + vl->previous = NULL; + lfree = vl; + vlink_count--; + string_count -= 4; /* freed name, host, filename, and args */ + } + + /* + * vllfree - free a VLINK structure + * + * VLLFREE takes a pointer to a VLINK structure frees it and any linked + * VLINK structures. It is used to free an entrie list of VLINK + * structures. + */ + + void vllfree(VLINK vl) + { + VLINK nxt; + + while((vl != NULL) && !vl->dontfree) { + nxt = vl->next; + vlfree(vl); + vl = nxt; + } + } + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/vms.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/vms.h:1.1 *** /dev/null Tue Oct 5 13:20:09 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/archie-client/vms.h Tue Oct 5 13:19:58 2004 *************** *** 0 **** --- 1,47 ---- + #ifndef _ARCHIE_VMS + #define _ARCHIE_VMS + #include + + #if !defined(MULTINET_30) && !defined(WOLLONGONG) && !defined(UCX) + #include "[.vms]pseudos.h" + #include "[.vms]types.h" + #include "[.vms]in.h" + #include "[.vms]signal.h" + #include "[.vms]socket.h" + #include "[.vms]time.h" + + #else + + /* time_t gets multiply defined */ + #ifndef __TYPES + #define __TYPES + #endif + #ifdef MULTINET_30 + # include "multinet_root:[multinet.include.sys]types.h" + # include "multinet_root:[multinet.include.netinet]in.h" + # include "multinet_root:[multinet.include.sys]socket.h" + # include "multinet_root:[multinet.include.sys]time.h" + #endif /* MULTINET_30 */ + + #ifdef WOLLONGONG + /* We don't want size_t defined. */ + # ifndef __STDDEF + # define __STDDEF + # endif + # include "twg$tcp:[netdist.include.sys]types.h" + # include "twg$tcp:[netdist.include.netinet]in.h" + # include "twg$tcp:[netdist.include.sys]socket.h" + # include "twg$tcp:[netdist.include.sys]time.h" + #endif /* WOLLONGONG */ + + #ifdef UCX + # include + # include + # include + # include + # include "[.vms]fd.h" + #endif /* UCX */ + + #endif /* Multinet or Wallongong or UCX */ + + #endif /* _ARCHIE_VMS */ From lattner at cs.uiuc.edu Tue Oct 5 13:23:45 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:23:45 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/ Message-ID: <200410051823.NAA22144@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 13:24:30 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:24:30 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/Makefile assem.c assem.h buffer.c buffer.h code.c code.h constants.h convert.c convert.h op_tab.c op_tab.h pass1.c pass1.h pass2.c pass2.h pseudo.c pseudo.h record.c record.h scan_line.c scan_line.h stringI.c stringI.h sym_tab.c sym_tab.h Message-ID: <200410051824.NAA22207@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler: Makefile added (r1.1) assem.c added (r1.1) assem.h added (r1.1) buffer.c added (r1.1) buffer.h added (r1.1) code.c added (r1.1) code.h added (r1.1) constants.h added (r1.1) convert.c added (r1.1) convert.h added (r1.1) op_tab.c added (r1.1) op_tab.h added (r1.1) pass1.c added (r1.1) pass1.h added (r1.1) pass2.c added (r1.1) pass2.h added (r1.1) pseudo.c added (r1.1) pseudo.h added (r1.1) record.c added (r1.1) record.h added (r1.1) scan_line.c added (r1.1) scan_line.h added (r1.1) stringI.c added (r1.1) stringI.h added (r1.1) sym_tab.c added (r1.1) sym_tab.h added (r1.1) --- Log message: Another benchmark. This is apparently an assembler for some target I couldn't figure out. There are also no input files for this :( Agg, and the source looks like pascal! --- Diffs of the changes: (+3184 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/Makefile:1.1 *** /dev/null Tue Oct 5 13:24:26 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/Makefile Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = assembler + LDFLAGS = -lm + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/assem.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/assem.c:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/assem.c Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,109 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================ assem.c ==================================== */ + /* Main (driving) routine of the assembler. Contains a few globals, opens */ + /* closes input, output, and temporary files. Calls Pass1 and Pass2 */ + + /* to compile (the assembler) use: */ + /* cc -o assem assem.c pass1.c pass2.c scan_line.c stringI.c sym_tab.c */ + /* op_tab.c pseudo.c code.c record.c buffer.c convert.c -lm */ + + #include + #include + #include + #include + #include "constants.h" + #include "pass1.h" + #include "pass2.h" + #include "sym_tab.h" + + /* --------------------------------- Globals ------------------------------ */ + /* MODULE_NAME Name of (program) module currently */ + /* assembling. */ + char MODULE_NAME[LABEL_SIZE_1+1]; + + /* MAIN_ROUTINE Name of (program) module declared with */ + /* a START (main routine). */ + char MAIN_ROUTINE[LABEL_SIZE_1+1]; + + /* START_ADDRESS Start Address for program execution. */ + int START_ADDRESS = -1; + + /* -------------------------------- main ---------------------------------- */ + int main(int argc,char **argv) + { + FILE *INPUT_STREAM; /* Input file stream */ + SYMBOL_TABLE SYM_TAB; /* The symbol table */ + FILE *TEMP_OUTPUT_STREAM; /* pass1 creates a file that is used as */ + /* as the input to pass2. */ + char *TEMP_OUTPUT_FILE_NAME /* Name of the above mentioned file */ + = "%pass1%"; + int ERROR = FALSE_1; /* FALSE no errors seen. TRUE seen errors */ + + INIT_SYM_TAB(&SYM_TAB); /* Initialize the symbol table */ + + if (argc == 1) (void) printf("usage: assem file\n"); + else { + if ( (INPUT_STREAM = fopen(argv[1],"r")) == NULL) { + (void) printf("%s: No such file or directory\n",argv[1]); + } else { + /* --------------------------------- Have a valid file: assemble it */ + char *LISTING_FILE; /* Name of file to put the listing into */ + FILE *LISTING_STREAM; /* Stream for listing file */ + char *OBJECT_FILE; /* Name of object code file */ + FILE *OBJECT_STREAM; /* Object code stream */ + int LOOP_COUNTER; /* a loop counter */ + + TEMP_OUTPUT_STREAM = fopen(TEMP_OUTPUT_FILE_NAME,"w"); + + PASS1(INPUT_STREAM,&SYM_TAB,TEMP_OUTPUT_STREAM); + (void) fclose(INPUT_STREAM); + (void) fclose(TEMP_OUTPUT_STREAM); + + /* --------------------------------- Get name for LISTING FILE */ + LISTING_FILE = (char *) malloc((unsigned int) (strlen(argv[1])+5)); + (void) strcpy(LISTING_FILE,argv[1]); + for ((LOOP_COUNTER = strlen(argv[1])); + ( (LOOP_COUNTER >= 0) && (LISTING_FILE[LOOP_COUNTER] != '.')); + LOOP_COUNTER --); + if (LOOP_COUNTER <= 0) LOOP_COUNTER = strlen(argv[1]); + (void) strcpy(&(LISTING_FILE[LOOP_COUNTER]),".lst"); + + /* --------------------------------- Get name for OBJECT FILE */ + OBJECT_FILE = (char *) malloc((unsigned int) (strlen(argv[1])+5)); + (void) strcpy(OBJECT_FILE,argv[1]); + (void) strcpy(&(OBJECT_FILE[LOOP_COUNTER]),".obj"); + + INPUT_STREAM = fopen(TEMP_OUTPUT_FILE_NAME,"r"); + LISTING_STREAM = fopen(LISTING_FILE,"w"); + OBJECT_STREAM = fopen(OBJECT_FILE,"w"); + + PASS2(INPUT_STREAM,OBJECT_STREAM,LISTING_STREAM,&SYM_TAB,&ERROR); + + (void) fclose(OBJECT_STREAM); + (void) fclose(LISTING_STREAM); + (void) fclose(INPUT_STREAM); + + /* -------------------------------- Delete the temporary output file */ + if (!DEBUG_FLAG_1) { + char *TEMP; + TEMP = (char *) malloc((unsigned int) + (4+strlen(TEMP_OUTPUT_FILE_NAME))); + (void) sprintf(TEMP,"rm %s",TEMP_OUTPUT_FILE_NAME); + (void) system(TEMP); + } + + /* -------------------------------- If errors, delete the object file */ + if (ERROR) { + char *TEMP; + TEMP = (char *) malloc((unsigned int) + (4+strlen(OBJECT_FILE))); + (void) sprintf(TEMP,"rm %s",OBJECT_FILE); + (void) system(TEMP); + (void) printf("Errors detected. Deleted object file.\n"); + } + } + } + return 1; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/assem.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/assem.h:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/assem.h Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,17 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================== assem.h ================================= */ + + #include "constants.h" + + /* MODULE_NAME Name of (program) module currently */ + /* assembling. */ + extern char MODULE_NAME[LABEL_SIZE_1+1]; + + /* MAIN_ROUTINE Name of (program) module declared with */ + /* a START (main routine). */ + extern char MAIN_ROUTINE[LABEL_SIZE_1+1]; + + /* START_ADDRESS Start Address for program execution. */ + extern int START_ADDRESS; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/buffer.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/buffer.c:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/buffer.c Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,101 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* =========================== buffer.c ==================================== */ + /* This module was created for 2 purposes: */ + /* 1) Store Modify records (of object code) till after all text */ + /* of a module (so that a modify record is always after the text */ + /* record for the same location) */ + /* 2) Store Error messages. Sometimes errors are detected that can */ + /* not be output immediately (in the middle of writting out */ + /* another record). This allows you to save error messages till */ + /* able to output them. */ + + #include + #include + #include + + /* Constants used to determine if being used to store modify records or */ + /* error messages. */ + #define MOD_REC_2 0 + #define ERROR_REC_2 1 + + + /* type BUFFER Linked list of strings */ + struct BUFFER { + char *LINE; + struct BUFFER *NEXT; + }; + + + /* type BUFFER_TYPE Pointers to both ends of the linked */ + /* list and whether contains */ + /* modification records or errors */ + struct BUFFER_TYPE { + struct BUFFER *HEAD_OF_BUFFER; + struct BUFFER *TAIL_OF_BUFFER; + int KIND; + }; + + + /* MOD_REC_BUF GLOBAL buffer for modification records*/ + struct BUFFER_TYPE MOD_REC_BUF = {NULL,NULL,MOD_REC_2}; + + /* ERROR_REC_BUF GLOBAL buffer for error messages */ + struct BUFFER_TYPE ERROR_REC_BUF = {NULL,NULL,ERROR_REC_2}; + + + + + /* ------------------------- OUTPUT_BUFFER --------------------------------- */ + /* Puts everything in buffer BUF into output stream OUTPUT. PASS (1 or 2) is */ + /* used as a fix to a problem I. In pass2, I call a procedure used by pass1, */ + /* which outputs errors in a different format. This is used to, in pass2, */ + /* convert the pass1 errors. Upon completion the buffer is empty. */ + + void OUTPUT_BUFFER(struct BUFFER_TYPE *BUF,FILE *OUTPUT,int PASS) + { + struct BUFFER *NEXT; + + /* --------------------------------- Step through the linked list, putting */ + /* --------------------------------- each string on a different line. */ + + while ((*BUF).HEAD_OF_BUFFER != NULL) { + NEXT =(* (*BUF).HEAD_OF_BUFFER).NEXT; + if ((PASS == 2) && !strncmp("eERROR",(*(*BUF).HEAD_OF_BUFFER).LINE,6)) + (void) fprintf(OUTPUT,"%s\n",&((*(*BUF).HEAD_OF_BUFFER).LINE[1])); + else + (void) fprintf(OUTPUT,"%s\n",(*(*BUF).HEAD_OF_BUFFER).LINE); + free((*(*BUF).HEAD_OF_BUFFER).LINE); + free((char *) (*BUF).HEAD_OF_BUFFER); + (*BUF).HEAD_OF_BUFFER = NEXT; + } + (*BUF).TAIL_OF_BUFFER = NULL; + } + + + /* ----------------------- ADD_TO_END_OF_BUFFER ---------------------------- */ + /* Puts the string INPUT_STR, on the end of the buffer pointed to by BUF. */ + + void ADD_TO_END_OF_BUFFER(struct BUFFER_TYPE *BUF,char *INPUT_STR) + { + char *TEMP_LINE; + /* --------------------------------- Create new element, and put on buffr */ + if ((*BUF).HEAD_OF_BUFFER == NULL) { + (*BUF).HEAD_OF_BUFFER = (struct BUFFER *) malloc(sizeof(struct BUFFER)); + (*BUF).TAIL_OF_BUFFER = (*BUF).HEAD_OF_BUFFER; + } else { + (*(*BUF).TAIL_OF_BUFFER).NEXT = (struct BUFFER *) malloc(sizeof(struct BUFFER)); + (*BUF).TAIL_OF_BUFFER = (*(*BUF).TAIL_OF_BUFFER).NEXT; + } + + /* --------------------------------- Initialize the buffer element correctly */ + (*(*BUF).TAIL_OF_BUFFER).LINE = TEMP_LINE = + malloc((unsigned int) (strlen(INPUT_STR) + 2)); + if ((*BUF).KIND == MOD_REC_2) { + TEMP_LINE[0] = 'M'; + (void) strcpy( &(TEMP_LINE[1]),INPUT_STR); + } else + (void) strcpy( TEMP_LINE,INPUT_STR); + (*(*BUF).TAIL_OF_BUFFER).NEXT = NULL; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/buffer.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/buffer.h:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/buffer.h Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,54 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ================================ buffer.h =============================== */ + /* This module was created for 2 purposes: */ + /* 1) Store Modify records (of object code) till after all text */ + /* of a module (so that a modify record is always after the text */ + /* record for the same location) */ + /* 2) Store Error messages. Sometimes errors are detected that can */ + /* not be output immediately (in the middle of writting out */ + /* another record). This allows you to save error messages till */ + /* able to output them. */ + + /* type BUFFER Linked list of strings */ + struct BUFFER { + char *LINE; + struct BUFFER *NEXT; + }; + + /* type BUFFER_TYPE Pointers to both ends of the linked */ + /* list and whether contains */ + /* modification records or errors */ + struct BUFFER_TYPE { + struct BUFFER *HEAD_OF_BUFFER; + struct BUFFER *TAIL_OF_BUFFER; + int KIND; + }; + + + /* MOD_REC_BUF GLOBAL buffer for modification records*/ + extern struct BUFFER_TYPE MOD_REC_BUF; + + /* ERROR_REC_BUF GLOBAL buffer for error messages */ + extern struct BUFFER_TYPE ERROR_REC_BUF; + + /* ------------------------- OUTPUT_BUFFER --------------------------------- */ + /* 3 parameters: */ + /* 1) struct BUFFER_TYPE *BUF; the buffer to output */ + /* 2) FILE *OUTPUT; the stream to output to */ + /* 3) int PASS; which pass called from 1 = pass1, */ + /* Puts everything in buffer BUF into output stream OUTPUT. PASS (1 or 2) is */ + /* used as a fix to a problem I. In pass2, I call a procedure used by pass1, */ + /* which outputs errors in a different format. This is used to, in pass2, */ + /* convert the pass1 errors. Upon completion the buffer is empty. */ + extern void OUTPUT_BUFFER(); + + /* ----------------------- ADD_TO_END_OF_BUFFER ---------------------------- */ + /* 2 parameters: */ + /* 1) struct BUFFER_TYPE *BUF; the buffer to add onto */ + /* 2) char *INPUT_STR; what to add onto the buffer */ + /* Puts the string INPUT_STR, on the end of the buffer pointed to by BUF. */ + extern void ADD_TO_END_OF_BUFFER(); + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/code.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/code.c:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/code.c Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,506 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================== code.c =================================== */ + /* Does the 'real' work of PASS2. Produces one listing file line for a */ + /* assembly instruction and all object file records, except those from pass1 */ + /* EVERY line of listing file is produced in this module (except pass1 */ + /* error messages). */ + /* Before this is called everything the assembler needs to know is figured */ + /* and this does (most of) the code generation. */ + + #include + #include + #include + #include + #include "pass1.h" + #include "stringI.h" + #include "scan_line.h" + #include "convert.h" + #include "sym_tab.h" + #include "record.h" + #include "assem.h" + #include "constants.h" + #include "buffer.h" + #include "op_tab.h" + + /* ------------------------------- PSEUDO_CODE (local) --------------------- */ + /* Generates listing line (except location counter which is handled */ + /* elsewhere) for source lines dealing with PSEUDO OPs. Produces object */ + /* records for pseudo ops that could not be figured at pass1 (line Header */ + /* records; do not know length until pass2). */ + + void PSEUDO_CODE(char *OPERATOR,FILE *INPUT_STREAM,FILE *OBJECT_STREAM, + FILE *LISTING_STREAM) + { + char CH; /* a character for looking ahead in the */ + /* input stream. */ + + /* -------------------------------- Output any generated machine code */ + if ( (strcmp(OPERATOR,"WORD")) && (strcmp(OPERATOR,"BYTE"))) + /* -------------------------------- Only BYTE and WORD generate code */ + /* (leave code part of listing blank) */ + /* COLUMNS 8 - 17 8901234567 */ + (void) fprintf(LISTING_STREAM," "); + else { + /* ---------------- Must look into pass1 output to see if any code generated */ + CH = fgetc(INPUT_STREAM); + if (CH == 't') { + /* -------------- Code in text record. Put into text record and listing file */ + /* -------------- put code into object file text records, and print on */ + /* -------------- listing line. */ + int LOCATION; + char TEMP_CH; + char *REST_OF_LINE; + + (void) fscanf(INPUT_STREAM,"%d%c",&LOCATION,&TEMP_CH); + GET_LINE(&REST_OF_LINE,INPUT_STREAM); + + (void) fprintf(LISTING_STREAM,"%s",REST_OF_LINE); + if (strlen(REST_OF_LINE) <= 8) { + int I; + for (I=(strlen(REST_OF_LINE)+1);I<=10;I++) + (void) fprintf(LISTING_STREAM," "); + } else + (void) fprintf(LISTING_STREAM, + /* COLUMNS 1 - 8 123456789012345678 */ + " {source on next line}\n "); + + if ( TEMP_CH == 'W') + ADD_TO_TEXT_RECORD(REST_OF_LINE,LOCATION,OBJECT_STREAM); + else { + char TEMP[HEX_CHAR_PER_BYTE_1+1]; + int DELTA = 0; + + for (TEMP[HEX_CHAR_PER_BYTE_1]='\0';!eoln(*REST_OF_LINE); + REST_OF_LINE+=HEX_CHAR_PER_BYTE_1) { + (void) strncpy(TEMP,REST_OF_LINE,HEX_CHAR_PER_BYTE_1); + ADD_TO_TEXT_RECORD(TEMP,(LOCATION+DELTA),OBJECT_STREAM); + DELTA ++; + } + } + } /* END if (CH == 't')*/ + else { + /* --------------- No code was generated for the BYTE/WORD because of errors */ + (void) ungetc(CH,INPUT_STREAM); + /* COLUMNS 8 - 17 8901234567 */ + (void) fprintf(LISTING_STREAM," "); + } + } + } + + /* ------------------------ GET_REG (local) -------------------------------- */ + /* Converts the next thing in a string (pointed to by REG) into the number */ + /* that corresponds to the register with that name. Returns -1 if next thing */ + /* is not a register. when done, *REG will point to the character immediately*/ + /* following the register name. */ + + int GET_REG(char **REG) + { + int VAL; + switch (**REG) { + case 'A': + VAL = 0; + break; + case 'X': + VAL = 1; + break; + case 'L': + VAL = 2; + break; + case 'B': + VAL = 3; + break; + case 'S': + if (*((*REG)+1) == 'W') { + (*REG) ++; + VAL = 9; + } else VAL = 4; + break; + case 'T': + VAL = 5; + break; + case 'P': + if (*((*REG)+1) == 'C') { + (*REG) ++; + VAL = 8; + } else VAL = -1; + break; + default: + VAL = -1; + break; + } + (*REG)++; + return VAL; + } + + + + /* ------------------------- SET_BITS_TO (local) --------------------------- */ + /* CODE is a 32 character string. Each element in that string is either a '0'*/ + /* or a '1' and represents the machine code for an instruction. SET_BITS_TO */ + /* sets the bits between LOW_BIT and HIGH_BIT (inclusive) so that they are */ + /* the binary equivalen to VALUE (i.e. make is so that: */ + /* SUM i=0 to (HIGH_BIT-LOW_BIT) {CODE[HIGH_BIT-i]*2^i} = VALUE. */ + + void SET_BITS_TO(int LOW_BIT,int HIGH_BIT,int VALUE,char *CODE) + { + int I; /* Loop counter variable */ + int BIT; /* BIT of code to set next */ + int VALUE_BIT; /* one BIT from VALUE to be moved to CODE*/ + + if ((HIGH_BIT < LOW_BIT) || (HIGH_BIT >= LARGEST_INSTRUCT_SIZE_1)) + (void) printf("SET_BITS_TO called improperly.\n"); + else { + BIT = HIGH_BIT; + for (I= ((int) pow(2.0,1.0*(HIGH_BIT-LOW_BIT))); I > 0; I /= 2) { + VALUE_BIT = VALUE - (VALUE/2)*2; + VALUE /= 2; + CODE[BIT] = ((char) VALUE_BIT) + '0'; + BIT --; + } + if (VALUE != 0) + (void) printf("SET_BITS_TO called improperly, VALUE too large.\n"); + } + } + + /* ----------------------- PRT_CODE (local) -------------------------------- */ + /* Output to OBJECT_STREAM, the number represented by the first BYTES bytes */ + /* of the [binary] string CODE. Also add the number to the TEXT Record of the*/ + /* object file (stream name is OBJECT_STREAM) at LOCATION. Output is */ + /* hexidecimal. */ + void PRT_CODE(char *CODE,int BYTES,int LOCATION,FILE *LISTING_STREAM, + FILE *OBJECT_STREAM) + { + int BYTE_COUNTER; /* byte to output next */ + int BIT_COUNTER; /* bit (of byte) to process next */ + int CH; + char NUM_STR[LARGEST_INSTRUCT_SIZE_1/4]; + + if (BYTES*4 > LARGEST_INSTRUCT_SIZE_1) + (void) printf("PRT_CODE called improperly.\n"); + else { + /* ------- Make a hex string representing the number. */ + for (BYTE_COUNTER=0;BYTE_COUNTER < BYTES; BYTE_COUNTER ++) { + CH = 0; + for (BIT_COUNTER=0; BIT_COUNTER < 4; BIT_COUNTER ++) + CH = CH * 2 + ((int) + CHAR_TO_DIGIT(CODE[BYTE_COUNTER*4+BIT_COUNTER],2)); + if ( (CH >= 0) && (CH <= 9)) + NUM_STR[BYTE_COUNTER] = (char) CH + '0'; + else NUM_STR[BYTE_COUNTER] = (char) (CH - 10) + 'A'; + } + NUM_STR[BYTES] = '\0'; + + /* ----------------------- Put Number into listing stream and object stream. */ + (void) fprintf(LISTING_STREAM,"%s",NUM_STR); + ADD_TO_TEXT_RECORD(NUM_STR,LOCATION,OBJECT_STREAM); + + for (BYTE_COUNTER = BYTES; BYTE_COUNTER < (LARGEST_INSTRUCT_SIZE_1/4); + BYTE_COUNTER ++) + (void) fprintf(LISTING_STREAM," "); + } + } + /* ------------------------------- REAL_CODE (local) ----------------------- */ + /* Generates listing line (except location counter which is handled */ + /* elsewhere) for source lines dealing with NON-PSEUDO OPs ('real' ops). */ + /* Produces object records for real ops. It also produces the text and */ + /* modification records (of object file) assocated with these source lines. */ + + void REAL_CODE(struct OP_ENTRY *OP_CODE,int EXTENDED,char *ARGUMENTS, + int LOCATION,SYMBOL_TABLE *SYM_TAB,FILE *OBJECT_STREAM, + FILE *LISTING_STREAM,int *ERROR) + { + char INSTRUCT_CODE[LARGEST_INSTRUCT_SIZE_1+1]; + int I; /* loop counter */ + int REG_NUMB; /* REGister NUMBer. Temporay storage*/ + + INSTRUCT_CODE[LARGEST_INSTRUCT_SIZE_1] = '\0'; + for (I=0;I= '0') && (*ARGUMENTS <= '4')) + SET_BITS_TO(8,11,(int) ((*ARGUMENTS) - '0'),INSTRUCT_CODE); + else { + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF, + "ERROR[43]: Illegal argument to SVC."); + (*ERROR) = TRUE_1; + } + ARGUMENTS ++; + } else + /* --------------------- First (maybe only) argument must be a register. */ + /* get it. */ + if ((REG_NUMB = GET_REG(&ARGUMENTS)) < 0) { + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF, + "ERROR[45]: Expected a valid register."); + (*ERROR) = TRUE_1; + ARGUMENTS ++; + } else { + SET_BITS_TO(8,11,REG_NUMB,INSTRUCT_CODE); + if ((*OP_CODE).OPERAND != REG) + /* -------------------- Two argument command, Get second after skipping comma*/ + if ((*ARGUMENTS) != ',') { + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF, + "ERROR[46]: Expected a comma after the first register."); + (*ERROR) = TRUE_1; + ARGUMENTS ++; + } else { + ARGUMENTS ++; + if ((*OP_CODE).OPERAND == REG_NUM) { + /* -------------------- Second argument must be a number 1-16 */ + REG_NUMB = CHAR_TO_DIGIT(*ARGUMENTS,10); + ARGUMENTS ++; + + if (REG_NUMB < 0) { + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF, + "ERROR[49]: Expected a number 1-16 after comma."); + (*ERROR) = TRUE_1; + ARGUMENTS ++; + } else { + if (CHAR_TO_DIGIT(*ARGUMENTS,10) >= 0) { + REG_NUMB = REG_NUMB*10+CHAR_TO_DIGIT(*ARGUMENTS,10); + ARGUMENTS ++; + REG_NUMB --; + } else REG_NUMB --; + if ((REG_NUMB < 0) || (REG_NUMB > 15)) { + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF, + "ERROR[49]: Expected a number 1-16 after comma."); + (*ERROR) = TRUE_1; + } + else SET_BITS_TO(12,15,REG_NUMB,INSTRUCT_CODE); + } + } else { + /* ---------------------- Second argument must be a register. */ + if ((REG_NUMB = GET_REG(&ARGUMENTS)) < 0) { + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF, + "ERROR[47]: Expected a valid register after the comma."); + (*ERROR) = TRUE_1; + } else + SET_BITS_TO(12,15,REG_NUMB,INSTRUCT_CODE); + } + } + } + + /* ---------------------- make sure nothing illegal after argument[s] */ + if (!IS_BLANK_OR_TAB(*ARGUMENTS) && !eoln(*ARGUMENTS)) { + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF, + "ERROR[44]: Expected a after the operand."); + (*ERROR) = TRUE_1; + } + + PRT_CODE(INSTRUCT_CODE,4,LOCATION,LISTING_STREAM,OBJECT_STREAM); + } /* END format TWO */ + + + if ((*OP_CODE).FORMAT == THREE_FOUR) { + /* ********************** Process FORMAT 3/4 instructions ****************** */ + int VALUE; /* value of argument */ + int WHAT_KIND = ABSOLUTE_OR_RELATIVE_1; /* type of argument */ + + /* ------ set extended bit correctly */ + SET_BITS_TO(11,11,EXTENDED,INSTRUCT_CODE); + if ((*OP_CODE).OPERAND == NONE) { + /* ------- RSUB has no arguments... easy */ + SET_BITS_TO(6,7,3,INSTRUCT_CODE); + if (EXTENDED) + PRT_CODE(INSTRUCT_CODE,8,LOCATION,LISTING_STREAM,OBJECT_STREAM); + else + PRT_CODE(INSTRUCT_CODE,6,LOCATION,LISTING_STREAM,OBJECT_STREAM); + } else { + /* ------ check for immediate or indirect mode, and set the bits accordingly */ + switch (*ARGUMENTS) { + case '@': + SET_BITS_TO(6,6,1,INSTRUCT_CODE); + ARGUMENTS ++; + break; + case '#': + SET_BITS_TO(7,7,1,INSTRUCT_CODE); + ARGUMENTS ++; + break; + default: + SET_BITS_TO(6,7,3,INSTRUCT_CODE); + } + /* ------- get the value of the argument and the type (kind) of that argument*/ + VALUE = GET_EXPRESSION(&ARGUMENTS,MEM_ADDR_SIZE_1+1, + LOCATION+1,SYM_TAB,&WHAT_KIND); + + if ( ERROR_REC_BUF.HEAD_OF_BUFFER != NULL) (*ERROR) = TRUE_1; + if ( ((*ARGUMENTS) == ',') && (*(ARGUMENTS+1) == 'X')) { + ARGUMENTS += 2; + SET_BITS_TO(8,8,1,INSTRUCT_CODE); + } + + if (EXTENDED) { + char MOD_REC[9]; + /* ------ 2's complement negative numbers */ + if (VALUE < 0) VALUE = MEM_SIZE_1 + VALUE; + if (WHAT_KIND == RELATIVE_VALUE_1) { + NUM_TO_STR(LOCATION+1,16,6,MOD_REC); + (void) strcat(MOD_REC,"05"); + ADD_TO_END_OF_BUFFER(&MOD_REC_BUF,MOD_REC); + } + SET_BITS_TO(12,31,VALUE,INSTRUCT_CODE); + PRT_CODE(INSTRUCT_CODE,8,LOCATION,LISTING_STREAM,OBJECT_STREAM); + } else { + /* ------- format 3's */ + if (WHAT_KIND == EXTERN_VALUE_1) { + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF, + "ERROR[53]: EXTREF label can not be used in a format THREE instruction."); + (*ERROR) = TRUE_1; + VALUE = 0; + } + if (WHAT_KIND == RELATIVE_VALUE_1) + VALUE = VALUE - (LOCATION + 3); + if ( ( (WHAT_KIND == RELATIVE_VALUE_1) && + (VALUE >= (MAX_PC_RELATIVE_1/2 ))) || + ( (WHAT_KIND != RELATIVE_VALUE_1) && + (VALUE >= (MAX_PC_RELATIVE_1)))) { + + if (WHAT_KIND == RELATIVE_VALUE_1) + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF, + "ERROR[51]: Location is not within PC relative range."); + else + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF, + "ERROR[52]: Constant too large for a format THREE instruction."); + (*ERROR) = TRUE_1; + VALUE = 0; + } + + + if (VALUE < 0) { + /* --------- 2's complement negative values */ + VALUE = MAX_PC_RELATIVE_1 + VALUE; + if ( (VALUE >= MAX_PC_RELATIVE_1) || + (VALUE < MAX_PC_RELATIVE_1 /2) ) { + if (WHAT_KIND == RELATIVE_VALUE_1) + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF, + "ERROR[51]: Location is not within PC relative range."); + else + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF, + "ERROR[52]: Constant too large for a format THREE instruction."); + (*ERROR) = TRUE_1; + VALUE = 0; + } + } + + SET_BITS_TO(12,23,VALUE,INSTRUCT_CODE); + if (WHAT_KIND == RELATIVE_VALUE_1) + SET_BITS_TO(10,10,1,INSTRUCT_CODE); + PRT_CODE(INSTRUCT_CODE,6,LOCATION,LISTING_STREAM,OBJECT_STREAM); + } + if (!IS_BLANK_OR_TAB(*ARGUMENTS) && !eoln(*ARGUMENTS)) { + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF, + "ERROR[44]: Expected a after the operand."); + (*ERROR) = 1; + } + } + } /* END format THREE_FOUR */ + + (void) fprintf(LISTING_STREAM," "); + } + + /* ================================= CODE ================================== */ + /* Determines the location counter value for a line, puts it into the */ + /* listing stream and calls the correct procedures to output the code */ + void CODE(FILE *INPUT_STREAM,SYMBOL_TABLE *SYM_TAB,FILE *OBJECT_STREAM, + FILE *LISTING_STREAM,int *ERROR) + { + char LABEL[LABEL_SIZE_1+1]; /* label on the source line */ + char OPERATOR[LABEL_SIZE_1+1]; /* operator on the source line */ + char *ARGUMENTS; /* source line after operator */ + char *INPUT_LINE; + int LOCATION_COUNTER; + int EXTENDED; /* is this an extended instruction? */ + struct OP_ENTRY *OP_CODE; + struct SYMBOL_TABLE_ENTRY *TABLE_ENTRY; + + (void) fscanf(INPUT_STREAM,"%d",&LOCATION_COUNTER); + (void) getc(INPUT_STREAM); /* remove space after s */ + + SCAN_LINE(LOCATION_COUNTER,&INPUT_LINE,LABEL,&EXTENDED,OPERATOR,&ARGUMENTS, + pass2,(FILE *) NULL,INPUT_STREAM); + + CAPITALIZE_STRING(LABEL); + CAPITALIZE_STRING(OPERATOR); + + OP_CODE = LOOK_UP_OP(OPERATOR); + if (!strcmp(LABEL,"") && !strcmp(OPERATOR,"") && (EXTENDED == 0)) + /* ----- blank source line */ + /* 123456789012345678 */ + (void) fprintf(LISTING_STREAM," %s\n",INPUT_LINE); + else { + if (!strcmp(OPERATOR,"")) { + /* --------- a no-op */ + PRT_NUM(LOCATION_COUNTER,16,6,LISTING_STREAM); + (void) fprintf(LISTING_STREAM," "); + } + + /* OUTPUT blanks for address, if PSEUDO OP that doesn't display a location */ + else if ((*OP_CODE).OPERAND == PSEUDO_NOLOC) + /* 1234567 */ + (void) fprintf(LISTING_STREAM," "); + + + else if ((*OP_CODE).OPERAND == PSEUDO_ADDR) { + /* -------- OUTPUT value as address if START,CSECT, or EQU */ + if (!strcmp(OPERATOR,"EQU")) { + TABLE_ENTRY = LOOK_UP_SYMBOL(MODULE_NAME,LABEL,SYM_TAB); + if (TABLE_ENTRY == NULL) + LOCATION_COUNTER = 0; + else LOCATION_COUNTER = (*TABLE_ENTRY).LOCATION; + } else { + if (!strcmp(LABEL,"")) + GET_NEXT_MISSING_LABEL(LABEL,SYM_TAB); + TABLE_ENTRY = LOOK_UP_SYMBOL(LABEL,LABEL,SYM_TAB); + if (TABLE_ENTRY == NULL) { + (void) printf( + "CODE: Something is wrong with code. This shouldn't be executed.\n"); + /* ------ In all other case output the location counter and the address */ + } else LOCATION_COUNTER = (*TABLE_ENTRY).LOCATION; + } + + PRT_NUM(LOCATION_COUNTER,16,6,LISTING_STREAM); + (void) fprintf(LISTING_STREAM," "); + } + else { + PRT_NUM(LOCATION_COUNTER,16,6,LISTING_STREAM); + (void) fprintf(LISTING_STREAM," "); + } + + { + char *SAVE_LINE; + + /* SAVE the source line so that other routines can mess it up without */ + /* worrying. This was necessary because PSEUDO_CODE might have to look a */ + /* whole line ahead in the input */ + SAVE_LINE = malloc((unsigned int) (strlen(INPUT_LINE) + 1)); + (void) strcpy(SAVE_LINE,INPUT_LINE); + CAPITALIZE_STRING(ARGUMENTS); + + /* call correct procedure to produce the code. */ + if ((*OP_CODE).FORMAT == NOT_FOUND) + /* COLUMNS 8 - 17 8901234567 */ + (void) fprintf(LISTING_STREAM," "); + else if ((*OP_CODE).FORMAT == PSEUDO) + PSEUDO_CODE(OPERATOR,INPUT_STREAM,OBJECT_STREAM,LISTING_STREAM); + else + REAL_CODE(OP_CODE,EXTENDED,ARGUMENTS,LOCATION_COUNTER, + SYM_TAB,OBJECT_STREAM,LISTING_STREAM,ERROR); + + (void) fprintf(LISTING_STREAM,"%s\n",SAVE_LINE); + free(SAVE_LINE); + } + } + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/code.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/code.h:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/code.h Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,22 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* =============================== code.h ================================== */ + /* Does the 'real' work of PASS2. Produces one listing file line for a */ + /* assembly instruction and all object file records, except those from pass1 */ + /* EVERY line of listing file is produced in this module (except pass1 */ + /* error messages). */ + /* Before this is called everything the assembler needs to know is figured */ + /* and this does (most of) the code generation. */ + + + /* ================================= CODE ================================== */ + /* 5 parameters: */ + /* 1) FILE *INPUT_STREAM; */ + /* 2) FILE *OBJECT_STREAM; */ + /* 3) FILE *LISTING_STREAM; */ + /* 4) SYMBOL_TABLE *SYM_TAB; symbol table to use */ + /* 5) int *ERROR; has an error been found (true/false)*/ + /* Determines the location counter value for a line, puts it into the */ + /* listing stream and calls the correct procedures to output the code */ + extern void CODE(); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/constants.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/constants.h:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/constants.h Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,61 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================= constants.h =============================== */ + /* A collection of commonly used constants for the assembler. */ + + + /* DEBUG_FLAG_1 Controls whether certain lines of the program. */ + /* Execution or non-execution of these lines aids in */ + /* Debugging the program. */ + #define DEBUG_FLAG_1 0 + + /* LABEL_SIZE_1 Size of the largest valid LABEL in characters */ + #define LABEL_SIZE_1 8 + + /* MEM_SIZE_1 Size of SIC/XE main memory in bytes */ + /* NOTE: 2^20 = 1048576 */ + #define MEM_SIZE_1 1048576 + + /* MEM_ADDR_SIZE_1 Number of BITS in an address {log2(MEM_SIZE_1)} */ + #define MEM_ADDR_SIZE_1 20 + + /* BITS_PER_WORD_1 Number of BITS in a WORD */ + #define BITS_PER_WORD_1 24 + + /* MAX_INT_1 Biggest integer+1: 2^BITS_PER_WORD_1 */ + #define MAX_INT_1 16777216 + + /* BITS_PER_HALFBYTE_1 Number of BITS in a Half BYTE */ + #define BITS_PER_HALFBYTE_1 4 + + /* BITS_PER_BYTE_2 Number of BITS in a BYTE */ + #define BITS_PER_BYTE_2 8 + + /* HEX_CHAR_PER_BYTE_1 Number of hexidecimal characters (ASCII) must be */ + /* used to produce a 1 BYTE value. */ + #define HEX_CHAR_PER_BYTE_1 2 + + /* LARGEST_INSTRUCT_SIZE_1 Size in BITS of the the largest instruction in */ + /* SIC/XE. Format 4 is 32 bits */ + #define LARGEST_INSTRUCT_SIZE_1 32 + + /* MAX_PC_RELATIVE_1 Smallest number that will NOT fit in a PC relative*/ + /* address. {4096 = 2^12} */ + #define MAX_PC_RELATIVE_1 4096 + + /* GLOBAL_1 Module name for Global labels -- used by LOADER. */ + #define GLOBAL_1 "_GLOBAL " + + /* -------------------------- Boolean Constants ---------------------------- */ + #define FALSE_1 0 + #define TRUE_1 1 + + + /* ------------------- Expression types (LABELS,CONSTANTS,etc) ------------- */ + #define ABSOLUTE_OR_RELATIVE_1 0 /* Don't know type */ + #define ABSOLUTE_VALUE_1 1 /* Absolute expressions */ + #define RELATIVE_VALUE_1 2 /* Relative expressions */ + #define EXTERN_VALUE_1 3 /* An external reference */ + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/convert.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/convert.c:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/convert.c Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,352 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================= convert.c ================================= */ + /* Contains routines that convert one thing to another. Most of the routines */ + /* deal with converting a number to a string of that number in some base, or */ + /* converting a string (assuming some base) into an integer. Basically */ + /* just a file of miscellaneous 'useful' routines. */ + #include + #include + #include + #include + #include "sym_tab.h" + #include "constants.h" + #include "scan_line.h" + #include "assem.h" + #include "buffer.h" + + + /* MISSING_LABEL_NAME Sections need names because the symbol */ + /* requires module names. MISSING_LABEL_NAME */ + /* is a global that is the name to the next */ + /* section that needs a name. */ + char MISSING_LABEL_NAME[3] = "_!"; + + /* ------------------------ RESET_MISSING_LABEL_NAME ----------------------- */ + /* Between pass1 and pass2, MISSING_LABEL_NAME must be reset to its */ + /* orginal value. This procedure does this. */ + void RESET_MISSING_LABEL_NAME() + { + (void) strcpy(MISSING_LABEL_NAME,"_!"); + } + + /* ------------------------ GET_NEXT_MISSING_LABEL ------------------------- */ + /* Puts MISSING_LABEL_NAME into string LABEL, and puts it into the symbol */ + /* table. It then changes MISSING_LABEL_NAME to some other unique name. */ + /* NOTE: this will only return about 90 unique names, after that it returns */ + /* the same name repeadily. This would result only some additional */ + /* previously defined label error messages. Never called when executed */ + /* on a source with no errors. */ + void GET_NEXT_MISSING_LABEL(char *LABEL,SYMBOL_TABLE *SYM_TAB) + { + char *CH; + + (void) strcpy(LABEL,MISSING_LABEL_NAME); + CH = &(MISSING_LABEL_NAME[strlen(MISSING_LABEL_NAME)-1]); + if ((*CH) < '\127') (*CH) = (*CH) + '\1'; + (void) INSERT_IN_SYM_TAB(MODULE_NAME,LABEL,0,RELATIVE,SYM_TAB); + } + + + /* ---------------------------- BLANK_STR ---------------------------------- */ + /* Set characters 0-7 of STRING to blank and make the 8th character NULL */ + /* ie. a 8 character string of blanks. */ + void BLANK_STR(char *STRING) + { + int I; + for (I=0;I < LABEL_SIZE_1; I ++) + STRING[I] = ' '; + STRING[LABEL_SIZE_1] = '\0'; + } + + /* ------------------------ CHAR_TO_DIGIT ---------------------------------- */ + /* Convert a character (CH) into its integer value give base NUM_BASE. Return*/ + /* -1 if it is not a valid digit in that base. */ + int CHAR_TO_DIGIT(char CH,int NUM_BASE) + { + int DIGIT = -1; + if ( (CH >= '0') && (CH <= '9') ) DIGIT = (int) (CH - '0'); + if ( (CH >= 'A') && (CH <= 'Z') ) DIGIT = ((int) (CH - 'A'))+10; + if (DIGIT >= NUM_BASE) DIGIT = -1; + return DIGIT; + } + + + /* ------------------------- NUM_TO_STR ------------------------------------ */ + /* Put into STR the string with LEN digits that represents the number NUM */ + /* in base BASE (eg. NUM_TO_STR(10,16,3,STR) puts "00A" in STR). */ + void NUM_TO_STR(int NUM,int BASE,int LEN,char *STR) + { + int I; /* loop counter */ + int DIGIT; /* one digit in base specified of NUM */ + + STR[LEN] = '\0'; + for (I=(LEN-1); I>=0; I--) { + DIGIT = NUM - (NUM/BASE) * BASE; + NUM /= BASE; + if ((DIGIT >= 0) && (DIGIT <= 9)) + STR[I] = (char) DIGIT + '0'; + else STR[I] = (char) (DIGIT-10) + 'A'; + } + if (NUM != 0) + (void) printf("NUM_TO_STR called illegally.\n"); + } + + /* -------------------------- PRT_NUM ------------------------------------- */ + /* Output (to stream OUTPUT) the string with LEN digits that represents the */ + /* number NUM in base BASE (eg. NUM_TO_STR(20,16,2,STR) puts "14" in STR). */ + void PRT_NUM(int NUM,int NUM_BASE,int LEN,FILE *OUTPUT) + { + int COUNT; /* loop counter */ + int MAX_NUM; /* Biggest number can represent with LEN */ + /* digits in base BASE */ + int DIGIT; /* One digit in base specified of NUM */ + + MAX_NUM = ((int) pow((NUM_BASE*1.0),(LEN-1)*1.0)); + + if (NUM < 0) NUM = MAX_NUM*NUM_BASE + NUM; + + if (NUM >= MAX_NUM * NUM_BASE) + (void) printf("ASSEMBLER ERROR: PRT_NUM called illegally.\n"); + + for (COUNT= MAX_NUM; COUNT >= 1; COUNT /= NUM_BASE) { + DIGIT = NUM / COUNT; + NUM = NUM - DIGIT*COUNT; + if ((DIGIT >= 0) && (DIGIT <= 9)) + (void) fprintf(OUTPUT,"%c",(char) (DIGIT + '0')); + else (void) fprintf(OUTPUT,"%c",(char) (DIGIT - 10 + 'A')); + } + + } + + + /* ------------------------------ GET_NUM ---------------------------------- */ + /* CURRENT_CHAR points to a string. Starting with the character */ + /* **CURRENT_CHAR and get the biggest possible integer in BASE NUM_BASE. If */ + /* that number is too large/small to fit in BITS bits (2's complement), */ + /* Put an error message into ERROR_REC_BUF. Returns 0 if this or any error is*/ + /* detected, otherwise it returns the integer representation of the number. */ + /* NOTE: If number is to large/small this routine stops as soon as it */ + /* realizes this w/o (with out) looking at the rest of the input. */ + int GET_NUM(char **CURRENT_CHAR,int BITS,int NUM_BASE) + { + int CONVERT = 0; /* CONVERT is the converted integer of the */ + /* string */ + int MAX_UNSIGNED_INT; /* MAX_UNSIGNED_INT = 2^(BITS-1) */ + /* - Biggest negative number */ + /* (w/o sign) that fits */ + /* - Biggest biggest number + 1 */ + /* (w/o sign) that fits */ + int SIGN = 1; /* Sign of the number- assume positive. */ + char *INPUT_START; /* Keeps track of where string started */ + int DIGIT; /* One digit of the number. */ + + MAX_UNSIGNED_INT = (int) pow(2.0,(BITS-1)*1.0); + INPUT_START = *CURRENT_CHAR; + + if ((**CURRENT_CHAR) == '-') + SIGN = -1; + else SIGN = 1; + + if ( ((**CURRENT_CHAR) == '-') || ((**CURRENT_CHAR) == '+')) { + /* ---------------------------- MUST be a valid digit after the sign */ + (*CURRENT_CHAR) ++; + if (CHAR_TO_DIGIT(**CURRENT_CHAR,NUM_BASE) == -1) { + char *ERROR_MSG; + ERROR_MSG = (char *) malloc((unsigned int) 80); + if (**CURRENT_CHAR > 0) + (void) sprintf(ERROR_MSG, + "eERROR[15]: Illegal Expression. Found '%c' after %c.", + **CURRENT_CHAR,*( (*CURRENT_CHAR) - 1)); + else + (void) sprintf(ERROR_MSG, + "eERROR[15]: Illegal Expression. Found '' after %c.", + *( (*CURRENT_CHAR) - 1)); + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF,ERROR_MSG); + free(ERROR_MSG); + } + } + + /* ----------------------------- Get the biggest [legal] number you can */ + while ( ( (DIGIT = CHAR_TO_DIGIT(**CURRENT_CHAR,NUM_BASE)) != -1) && + !eoln(**CURRENT_CHAR) ) { + if (CONVERT <= MAX_UNSIGNED_INT) + CONVERT = CONVERT*NUM_BASE + DIGIT; + (*CURRENT_CHAR) ++; + } + + /* ----------------------------- Make sure number is not to big or small */ + if ( ((CONVERT > MAX_UNSIGNED_INT) && (SIGN == -1)) || + ((CONVERT > (MAX_UNSIGNED_INT - 1)) && (SIGN == 1)) ) { + char SAV_CHAR; + char *ERROR_MSG; + + SAV_CHAR = **CURRENT_CHAR; + **CURRENT_CHAR = '\0'; + ERROR_MSG = (char *) malloc((unsigned int) + (80+ ((int) log10((double) NUM_BASE)) + + ((int) log10((double) MAX_UNSIGNED_INT)) +strlen(INPUT_START))); + + if (SIGN == 1) + (void) sprintf(ERROR_MSG, + "eERROR[10]: %s[%d] is too large for it's intended use (MAX %d[10]).", + INPUT_START,NUM_BASE,MAX_UNSIGNED_INT - 1); + else + (void) sprintf(ERROR_MSG, + "eERROR[11]: %s[%d] is too small for it's intended use (MIN %d[10]).", + INPUT_START,NUM_BASE,-1*MAX_UNSIGNED_INT); + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF,ERROR_MSG); + free(ERROR_MSG); + **CURRENT_CHAR = SAV_CHAR; + CONVERT = 0; + } + + return CONVERT*SIGN; + } + + + /* ---------------------------- GET_EXPRESSION ----------------------------- */ + /* Is used to find an expression (well, for now actually it can have no */ + /* operations, just single terms). Caller can specify what kind of expression*/ + /* is needed (ABSOLUTE or RELATIVE) or can specify that either kind is okay. */ + /* Sets WHAT_KIND to they type (kind) of expression found. */ + int GET_EXPRESSION(char **CURRENT_CHAR,int BITS,int LOCATION, + SYMBOL_TABLE *SYM_TAB,int *WHAT_KIND) + { + char *START; /* remember where the expression */ + /* started in string. */ + START = (*CURRENT_CHAR); + + /* ------------------ Check if a decimal constant, if so get it */ + if ((*WHAT_KIND != RELATIVE_VALUE_1) && + ( ( ((**CURRENT_CHAR) >= '0') && ((**CURRENT_CHAR) <= '9') ) || + ((**CURRENT_CHAR) == '-') || ((**CURRENT_CHAR) == '+') )) + { + (*WHAT_KIND) = ABSOLUTE_VALUE_1; + return GET_NUM(CURRENT_CHAR,BITS,10); + } + + /* ------------------ Check if hexidecimal constant, if so, get it */ + if ((*WHAT_KIND != RELATIVE_VALUE_1) && + ( ((**CURRENT_CHAR) == 'X') && (*((*CURRENT_CHAR)+1) == '\'')) ) { + int RESULT; + + (*WHAT_KIND) = ABSOLUTE_VALUE_1; + (*CURRENT_CHAR) += 2; + RESULT = GET_NUM(CURRENT_CHAR,BITS,16); + /* --------------------------- Check for error messages */ + if ( (**CURRENT_CHAR) != '\'') { + while ( (**CURRENT_CHAR != '\'') && (!eoln(**CURRENT_CHAR)) ) + (*CURRENT_CHAR) ++; + if (eoln(**CURRENT_CHAR)) { + char ERROR_MSG[80]; + (void) sprintf(ERROR_MSG, + "eERROR[16]: Illegal Hexidecimal. Expected close quote."); + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF,ERROR_MSG); + } else { + char TEMP; + char *ERROR_MSG; + + (*CURRENT_CHAR) ++; + + TEMP = **CURRENT_CHAR; + **CURRENT_CHAR = '\0'; + + ERROR_MSG = (char *) malloc((unsigned int) + (80+ strlen(START))); + + (void) sprintf(ERROR_MSG, + "eERROR[17]: Illegal Hexidecimal. %s",START); + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF,ERROR_MSG); + free(ERROR_MSG); + **CURRENT_CHAR = TEMP; + } + } + else (*CURRENT_CHAR) ++; + return RESULT; + } + + /* ----------------------------- Must be a label, get it */ + { + char LABEL_NAME[LABEL_SIZE_1 + 1]; + struct SYMBOL_TABLE_ENTRY *LABEL_INFO; + + GET_LABEL(LABEL_NAME,*CURRENT_CHAR,CURRENT_CHAR,pass1); + + if (!strcmp(LABEL_NAME,"")) { + /* ----------------------------- There was no label. ERROR */ + char *ERROR_MSG; + + ERROR_MSG = (char *) malloc((unsigned int) + (80+ strlen(*CURRENT_CHAR))); + (void) sprintf(ERROR_MSG, + "eERROR[14]: Expected an expression, found '%s'.", + *CURRENT_CHAR); + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF,ERROR_MSG); + free(ERROR_MSG); + } + else { + /* ----------------------------- Get the value of the LABEL */ + LABEL_INFO = LOOK_UP_SYMBOL(MODULE_NAME,LABEL_NAME,SYM_TAB); + if (LABEL_INFO == NULL) { + /* ----------------------------- has no value */ + char *ERROR_MSG; + + ERROR_MSG = (char *) malloc((unsigned int) + (80+ strlen(LABEL_NAME))); + if ((*WHAT_KIND) != ABSOLUTE_OR_RELATIVE_1) + (void) sprintf(ERROR_MSG, + "eERROR[24]: %s is not a defined symbol or is forwardly declared.", + LABEL_NAME); + else + (void) sprintf(ERROR_MSG,"eERROR[49]: %s is not a defined symbol.", + LABEL_NAME); + + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF,ERROR_MSG); + free(ERROR_MSG); + } else + if ( (*WHAT_KIND != RELATIVE_VALUE_1) && + ((*LABEL_INFO).TYPE == ABSOLUTE)) { + (*WHAT_KIND) = ABSOLUTE_VALUE_1; + return (*LABEL_INFO).LOCATION; + } else + if ( (*WHAT_KIND != ABSOLUTE_VALUE_1) && + ((*LABEL_INFO).TYPE != ABSOLUTE)) { + if ((*LABEL_INFO).TYPE == EXTERN_REF) { + /* ----------------------- Value needs a modification record */ + char OUTPUT_LINE[9+LABEL_SIZE_1]; + char FIX_LEN_NAME[LABEL_SIZE_1+1]; + char LEN_STR[3]; + + NUM_TO_STR(LOCATION,16,6,OUTPUT_LINE); + NUM_TO_STR((BITS/4),16,2,LEN_STR); + (void) strcat(OUTPUT_LINE,LEN_STR); + (void) strcat(OUTPUT_LINE,"+"); + BLANK_STR(FIX_LEN_NAME); + (void) strncpy(FIX_LEN_NAME,LABEL_NAME,strlen(LABEL_NAME)); + (void) strcat(OUTPUT_LINE,FIX_LEN_NAME); + ADD_TO_END_OF_BUFFER(&MOD_REC_BUF,OUTPUT_LINE); + (*WHAT_KIND) = EXTERN_VALUE_1; + } else (*WHAT_KIND) = RELATIVE_VALUE_1; + return (*LABEL_INFO).LOCATION; + } else { + char *ERROR_MSG; + + ERROR_MSG = (char *) malloc((unsigned int) + (80+ strlen(LABEL_NAME))); + if (*WHAT_KIND == ABSOLUTE_VALUE_1) + (void) sprintf(ERROR_MSG, + "eERROR[25]: %s is a LABEL, expected a CONSTANT.", + LABEL_NAME); + else + (void) sprintf(ERROR_MSG, + "eERROR[50]: %s is a CONSTANT, expected a LABEL.", + LABEL_NAME); + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF,ERROR_MSG); + free(ERROR_MSG); + } + } + return 0; + } + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/convert.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/convert.h:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/convert.h Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,96 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* =============================== convert.h =============================== */ + /* Contains routines that convert one thing to another. Most of the routines */ + /* deal with converting a number to a string of that number in some base, or */ + /* converting a string (assuming some base) into an integer. Basically */ + /* just a file of miscellaneous 'useful' routines. */ + + /* ------------------------ RESET_MISSING_LABEL_NAME ----------------------- */ + /* No parmeters: */ + /* Between pass1 and pass2, MISSING_LABEL_NAME must be reset to its */ + /* orginal value. This procedure does this. */ + extern void RESET_MISSING_LABEL_NAME(); + + /* ------------------------ GET_NEXT_MISSING_LABEL ------------------------- */ + /* 2 parameters: */ + /* 1) char *LABEL; String to put label into */ + /* 2) SYMBOL_TABLE *SYM_TAB; symbol table to insert the label in*/ + /* Puts MISSING_LABEL_NAME into string LABEL, and puts it into the symbol */ + /* table. It then changes MISSING_LABEL_NAME to some other unique name. */ + /* NOTE: this will only return about 90 unique names, after that it returns */ + /* the same name repeadily. This would result only some additional */ + /* previously defined label error messages. Never called when executed */ + /* on a source with no errors. */ + extern void GET_NEXT_MISSING_LABEL(); + + /* ---------------------------- BLANK_STR ---------------------------------- */ + /* 1 paramter: */ + /* char *STRING; String to blank out */ + /* Set characters 0-7 of STRING to blank and make the 8th character NULL */ + /* ie. a 8 character string of blanks. */ + extern void BLANK_STR(); + + /* ------------------------ CHAR_TO_DIGIT ---------------------------------- */ + /* 2 parameters: */ + /* 1) char CH; character to convert */ + /* 2) int NUM_BASE; base of number */ + /* Convert a character (CH) into its integer value give base NUM_BASE. Return*/ + /* -1 if it is not a valid digit in that base. */ + extern int CHAR_TO_DIGIT(); + + /* ------------------------- NUM_TO_STR ------------------------------------ */ + /* 4 parameters: */ + /* 1) int NUM; Number to convert */ + /* 2) int BASE; Base to convert into */ + /* 3) int LEN; Number of digits in final string */ + /* 4) char *STR; where to put it. */ + /* Put into STR the string with LEN digits that represents the number NUM */ + /* in base BASE (eg. NUM_TO_STR(10,16,3,STR) puts "00A" in STR). */ + extern void NUM_TO_STR(); + + /* -------------------------- PRT_NUM ------------------------------------- */ + /* 4 parameters: */ + /* 1) int NUM; Number to print out */ + /* 2) int NUM_BASE; Base to print it out in */ + /* 3) int LEN; Number of digits to print out. */ + /* 4) FILE *OUTPUT; Stream to output the number to */ + /* Output (to stream OUTPUT) the string with LEN digits that represents the */ + /* number NUM in base BASE (eg. NUM_TO_STR(20,16,2,STR) puts "14" in STR). */ + extern void PRT_NUM(); + + /* ------------------------------ GET_NUM ---------------------------------- */ + /* 3 parameters: */ + /* 1) char **CURRENT_CHAR; pointer to start of string to interpret */ + /* as an integer (in NUM_BASE) */ + /* 2) int BITS; Number must fit in this may bits 2's */ + /* complement. */ + /* 3) int NUM_BASE; * Base the number is in. */ + /* CURRENT_CHAR points to a string. Starting with the character */ + /* **CURRENT_CHAR and get the biggest possible integer in BASE NUM_BASE. If */ + /* that number is too large/small to fit in BITS bits (2's complement), */ + /* Put an error message into ERROR_REC_BUF. Returns 0 if this or any error is*/ + /* detected, otherwise it returns the integer representation of the number. */ + /* NOTE: If number is to large/small this routine stops as soon as it */ + /* realizes this w/o (with out) looking at the rest of the input. */ + extern int GET_NUM(); + + /* ---------------------------- GET_EXPRESSION ----------------------------- */ + /* 5 parameters: */ + /* 1) char **CURRENT_CHAR; Where to look for the expression */ + /* 2) int BITS; value of the expression must fit in */ + /* BITS 2's complement */ + /* 3) int LOCATION; LOCATION this number is to go into */ + /* this is needed for modification */ + /* records when referencing an EXTREF */ + /* 4) SYMBOL_TABLE *SYM_TAB; The symbol table */ + /* 5) int *WHAT_KIND; Initially whether the caller wants */ + /* Relative or absolute or either type */ + /* of expression. At termination its */ + /* the kind found. */ + /* Is used to find an expression (well, for now actually it can have no */ + /* operations, just single terms). Caller can specify what kind of expression*/ + /* is needed (ABSOLUTE or RELATIVE) or can specify that either kind is okay. */ + /* Sets WHAT_KIND to they type (kind) of expression found. */ + extern int GET_EXPRESSION(); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/op_tab.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/op_tab.c:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/op_tab.c Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,96 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================== op_tab =================================== */ + /* Defines and allows for loop up in the OPERATOR TABLE */ + #include + #include "pseudo.h" + + /* ---------------- Possible formats for instructions. */ + enum formats {ONE,TWO,THREE_FOUR,PSEUDO,NOT_FOUND}; + /* ---------------- Possible operand types --------------------------------- */ + enum operands + {NONE,REG,REG_REG,MEM,REG_NUM,NUM,PSEUDO_LOC,PSEUDO_NOLOC,PSEUDO_ADDR}; + + /* ---------------- Structure of the operator table */ + struct OP_ENTRY { + char *MNEMONIC; /* Name of the operator */ + enum formats FORMAT; /* FORMAT of this operator */ + char *OPCODE; /* OPCODE for this operator */ + enum operands OPERAND; /* Number and type of operands */ + int FUNCTION; /* Function to execute is PASS1. Pseudo */ + /* operators only. */ + }; + + + #define NUM_OPCODES 59 /* number of opcodes in the table */ + /* NOT counting the NOT_FOUND entry */ + + /* table (sorted array) of keywords used in EMITID */ + struct OP_ENTRY OP_TABLE[] = + {{"ADD",THREE_FOUR,"18",MEM,NULL}, + {"ADDR",TWO,"90",REG_REG,NULL}, + {"AND",THREE_FOUR,"40",MEM,NULL}, + {"BYTE",PSEUDO," ",PSEUDO_LOC,PSEUDO_BYTE0}, + {"CLEAR",TWO,"B4",REG,NULL}, + {"COMP",THREE_FOUR,"28",MEM,NULL}, + {"COMPR",TWO,"A0",REG_REG,NULL}, + {"CSECT",PSEUDO," ",PSEUDO_ADDR,PSEUDO_CSECT0}, + {"DIV",THREE_FOUR,"24",MEM,NULL}, {"DIVR",TWO,"9C",REG_REG,NULL}, + {"END",PSEUDO," ",PSEUDO_LOC,PSEUDO_END0}, + {"EQU",PSEUDO," ",PSEUDO_ADDR,PSEUDO_EQU0}, + {"EXTDEF",PSEUDO," ",PSEUDO_NOLOC,PSEUDO_EXTDEF0}, + {"EXTREF",PSEUDO," ",PSEUDO_NOLOC,PSEUDO_EXTREF0}, + {"HIO",ONE,"F4",NONE,NULL}, {"J",THREE_FOUR,"3C",MEM,NULL}, + {"JEQ",THREE_FOUR,"30",MEM,NULL}, {"JGT",THREE_FOUR,"34",MEM,NULL}, + {"JLT",THREE_FOUR,"38",MEM,NULL}, {"JSUB",THREE_FOUR,"48",MEM,NULL}, + {"LDA",THREE_FOUR,"00",MEM,NULL}, {"LDB",THREE_FOUR,"68",MEM,NULL}, + {"LDCH",THREE_FOUR,"50",MEM,NULL}, {"LDL",THREE_FOUR,"08",MEM,NULL}, + {"LDS",THREE_FOUR,"6C",MEM,NULL}, {"LDT",THREE_FOUR,"74",MEM,NULL}, + {"LDX",THREE_FOUR,"04",MEM,NULL}, {"LPS",THREE_FOUR,"D0",MEM,NULL}, + {"MUL",THREE_FOUR,"20",MEM,NULL}, {"MULR",TWO,"98",REG_REG,NULL}, + {"OR",THREE_FOUR,"44",MEM,NULL}, {"RD",THREE_FOUR,"D8",MEM,NULL}, + {"RESB",PSEUDO," ",PSEUDO_LOC,PSEUDO_RESB0}, + {"RESW",PSEUDO," ",PSEUDO_LOC,PSEUDO_RESW0}, + {"RMO",TWO,"AC",REG_REG,NULL}, {"RSUB",THREE_FOUR,"4C",NONE,NULL}, + {"SHIFTL",TWO,"A4",REG_NUM,NULL}, {"SHIFTR",TWO,"A8",REG_NUM,NULL}, + {"SIO",ONE,"F0",NONE,NULL}, {"SSK",THREE_FOUR,"EC",MEM,NULL}, + {"STA",THREE_FOUR,"0C",MEM,NULL}, + {"START",PSEUDO," ",PSEUDO_ADDR,PSEUDO_START0}, + {"STB",THREE_FOUR,"78",MEM,NULL}, {"STCH",THREE_FOUR,"54",MEM,NULL}, + {"STI",THREE_FOUR,"D4",MEM,NULL}, {"STL",THREE_FOUR,"14",MEM,NULL}, + {"STS",THREE_FOUR,"7C",MEM,NULL}, {"STSW",THREE_FOUR,"E8",MEM,NULL}, + {"STT",THREE_FOUR,"84",MEM,NULL}, {"STX",THREE_FOUR,"10",MEM,NULL}, + {"SUB",THREE_FOUR,"1C",MEM,NULL}, {"SUBR",TWO,"94",REG_REG,NULL}, + {"SVC",TWO,"B0",NUM,NULL}, {"TD",THREE_FOUR,"E0",MEM,NULL}, + {"TIO",ONE,"F8",NONE,NULL}, {"TIX",THREE_FOUR,"2C",MEM,NULL}, + {"TIXR",TWO,"B8",REG,NULL}, {"WD",THREE_FOUR,"DC",MEM,NULL}, + {"WORD",PSEUDO," ",PSEUDO_LOC,PSEUDO_WORD0}, + /* the next entry must always be last */ + {"*END OF TABLE*",NOT_FOUND,"00",NONE,NULL}}; + + + /* ---------------------------- LOOK_UP_OP --------------------------------- */ + /* Find operator in the table. Return the entry if it is found, else return */ + /* the not found entry. Uses BINARY SEARCH. */ + struct OP_ENTRY *LOOK_UP_OP(char OP[]) + { + int LOW = 0, /* LOWest element in OP_TABLE that may be the OP */ + HIGH = NUM_OPCODES-1,/* HIGHest element that may be the OP */ + MIDDLE; /* (LOW+HIGH)/2... next element considering */ + + int CMP; /* stores the result of a string comparison; */ + /* 0 str1 = str2, 1 str1 > str2, -1 str1 < str2 */ + + MIDDLE = 0; + while (LOW <= HIGH) + { + MIDDLE = (HIGH + LOW)/2; + if (!(CMP = strcmp(OP_TABLE[MIDDLE].MNEMONIC,OP))) + return &OP_TABLE[MIDDLE]; + if (CMP > 0) + HIGH = MIDDLE - 1; + else LOW = MIDDLE + 1; + } + return &OP_TABLE[NUM_OPCODES]; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/op_tab.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/op_tab.h:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/op_tab.h Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,29 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================ op_tab.h =================================== */ + + /* ---------------- Possible formats for instructions. */ + enum formats {ONE,TWO,THREE_FOUR,PSEUDO,NOT_FOUND}; + + /* ---------------- Possible operand types --------------------------------- */ + enum operands + {NONE,REG,REG_REG,MEM,REG_NUM,NUM,PSEUDO_LOC,PSEUDO_NOLOC,PSEUDO_ADDR}; + + /* ---------------- Structure of the operator table */ + struct OP_ENTRY { + char *MNEMONIC; /* Name of the operator */ + enum formats FORMAT; /* FORMAT of this operator */ + char *OPCODE; /* OPCODE for this operator */ + enum operands OPERAND; /* Number and type of operands */ + int FUNCTION; /* Function to execute is PASS1. Pseudo */ + /* operators only. */ + }; + + /* ---------------------------- LOOK_UP_OP --------------------------------- */ + /* 1 parameter: */ + /* 1) char OP[]; Name of the OPerator to find. */ + /* Find operator in the table. Return the entry if it is found, else return */ + /* the not found entry. Uses BINARY SEARCH. */ + extern struct OP_ENTRY *LOOK_UP_OP(); + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pass1.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pass1.c:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pass1.c Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,164 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================== pass1.c ================================== */ + /* Drives pass1 of the assembler, but lets other routines do the real work */ + + #include + #include "assem.h" + #include "scan_line.h" + #include "sym_tab.h" + #include "op_tab.h" + #include "convert.h" + #include "buffer.h" + #include "constants.h" + #include "pseudo.h" + + #define START_LEGAL_1 0 /* = May see a START legally */ + #define SEEN_START_1 1 /* = Have seen a START */ + /* SEND_START_OP Global that contains whether or not */ + /* a START operator has been seen */ + int SEEN_START_OP = START_LEGAL_1; + + + #define NO_END_SEEN_1 0 /* = Haven't seen an END */ + #define END_SEEN_1 1 /* = Have seen an END but haven't */ + /* found any code after it */ + #define END_SEEN_WITH_CODE_1 2 /* = Have seen an END and code after it */ + #define START_OF_CODE_1 3 /* = Start of code */ + /* SEEN_END_OP Flag to determine if seen an end since */ + /* start of last module or not. If so it */ + /* also indicated if any code seen since */ + /* end (so only one 'code after end' error */ + /* is generated. */ + int SEEN_END_OP = START_OF_CODE_1; + + /* LOCATION_EXCEEDS_MEM_SIZE Indicates if location counter is greater*/ + /* then the memory size. */ + int LOCATION_EXCEEDS_MEM_SIZE = FALSE_1; + + /* -------------------------- CHANGE_LOCATION ------------------------------ */ + /* LOCATION = LOCATION + INCREMENT unless this puts LOCATION past MEM_SIZE, */ + /* or if the location has already exceeded the memory size. */ + void CHANGE_LOCATION(int *LOCATION,int INCREMENT,FILE *OUTPUT) + { + if (!LOCATION_EXCEEDS_MEM_SIZE) + if ( ((*LOCATION + INCREMENT) > MEM_SIZE_1) || (*LOCATION == MEM_SIZE_1)) + { + LOCATION_EXCEEDS_MEM_SIZE = TRUE_1; + (void) fprintf(OUTPUT, + "eERROR[12]: Location exceeds the memory size (%d)\n", + MEM_SIZE_1); + (*LOCATION) = MEM_SIZE_1 - 1; + } else (*LOCATION) += INCREMENT; + } + + /* ---------------------- CAPITALIZE_STRING -------------------------------- */ + /* Make all lower case letters in the string STR upper case letters */ + void CAPITALIZE_STRING(char STR[]) + { + int I; + for (I=0; I<= (strlen(STR)); I++) + if ((STR[I] >= 'a') && (STR[I] <= 'z')) + STR[I] = STR[I] - 'a' + 'A'; + } + + /* --------------------------- PASS1 --------------------------------------- */ + /* Drives the pass1 process, letting others do the real work. */ + void PASS1(FILE *INPUT_FILE,SYMBOL_TABLE *SYM_TABLE,FILE *TEMP_OUTPUT_STREAM) + { + char LABEL_NAME[LABEL_SIZE_1+1]; /* Place to store a label. */ + char OPCODE[LABEL_SIZE_1+1]; /* Place to store an opcode. */ + char *ARGUMENTS; /* Pointer to arguments/comments */ + char *INPUT_LINE; /* Pointer to whole source line */ + int EXTENDED_CODE; /* Boolean: Is this an extended */ + /* format instruction. */ + + int LOCATION_COUNTER =0; + MODULE_NAME[0] = '_'; + MODULE_NAME[1] = '\0'; + + (void) INSERT_IN_SYM_TAB(MODULE_NAME,MODULE_NAME,0,RELATIVE,SYM_TABLE); + + MAIN_ROUTINE[0] = '\0'; + LABEL_NAME[0] = '\0'; + + while (!feof(INPUT_FILE)){ + /* --------------------- Get the source line and do some parsing */ + SCAN_LINE(LOCATION_COUNTER,&INPUT_LINE,LABEL_NAME, + &EXTENDED_CODE,OPCODE,&ARGUMENTS,pass1, + TEMP_OUTPUT_STREAM,INPUT_FILE); + + CAPITALIZE_STRING(LABEL_NAME); + CAPITALIZE_STRING(OPCODE); + CAPITALIZE_STRING(ARGUMENTS); + + if (( strcmp(LABEL_NAME,"") || strcmp(OPCODE,"") || EXTENDED_CODE) + && (SEEN_END_OP == END_SEEN_1) && strcmp(OPCODE,"CSECT") + && strcmp(OPCODE,"START")) { + (void) fprintf(TEMP_OUTPUT_STREAM, + "eERROR[30]: Statements following END.\n"); + SEEN_END_OP = END_SEEN_WITH_CODE_1; + } + + if (strcmp(LABEL_NAME,"")) + if ( LOOK_UP_SYMBOL(MODULE_NAME,LABEL_NAME,SYM_TABLE) == NULL) { + CHANGE_LOCATION(&LOCATION_COUNTER,0,TEMP_OUTPUT_STREAM); + if (!LOCATION_EXCEEDS_MEM_SIZE) + (void) INSERT_IN_SYM_TAB(MODULE_NAME,LABEL_NAME,LOCATION_COUNTER, + RELATIVE,SYM_TABLE); + } + else (void) fprintf(TEMP_OUTPUT_STREAM, + "eERROR[6]: %s is a multipy defined label.\n", + LABEL_NAME); + + if (strcmp(OPCODE,"")) + { + /* --------- Have an OPERATOR. Change location counter depending on format. */ + struct OP_ENTRY *OPCODE_INFO; + switch ( (*(OPCODE_INFO = LOOK_UP_OP(OPCODE))).FORMAT) + { + case NOT_FOUND: (void) fprintf(TEMP_OUTPUT_STREAM, + "eERROR[9]: %s is not a legal OPCODE.\n",OPCODE); + break; + case ONE: CHANGE_LOCATION(&LOCATION_COUNTER,1,TEMP_OUTPUT_STREAM); + if (EXTENDED_CODE) + (void) fprintf(TEMP_OUTPUT_STREAM, + "eERROR[8]: + is an illegal prefix to %s.",OPCODE); + break; + case TWO: CHANGE_LOCATION(&LOCATION_COUNTER,2,TEMP_OUTPUT_STREAM); + if (EXTENDED_CODE) + (void) fprintf(TEMP_OUTPUT_STREAM, + "eERROR[8]: + is an illegal prefix to %s.",OPCODE); + break; + case THREE_FOUR: if (EXTENDED_CODE) + CHANGE_LOCATION(&LOCATION_COUNTER,4,TEMP_OUTPUT_STREAM); + else CHANGE_LOCATION(&LOCATION_COUNTER,3,TEMP_OUTPUT_STREAM); + break; + case PSEUDO: if (EXTENDED_CODE) + (void) fprintf(TEMP_OUTPUT_STREAM, + "eERROR[8]: + is an illegal prefix to %s.",OPCODE); + + /* ************************************************************************* */ + /* The following instruction calls the correct procedure to do what needs to */ + /* be done for a particular pseudo operator. The operator table contains */ + /* the pointer to the correct routine. */ + DO_PSEUDO((*OPCODE_INFO).FUNCTION,LABEL_NAME,ARGUMENTS, + &LOCATION_COUNTER,SYM_TABLE,TEMP_OUTPUT_STREAM); + break; + } + } + + if ((SEEN_END_OP == START_OF_CODE_1) && + (strcmp(OPCODE,"") || strcmp(LABEL_NAME,""))) { + SEEN_END_OP = NO_END_SEEN_1; + (void) fprintf(TEMP_OUTPUT_STREAM, + "eERROR[35]: No START/CSECT found before statements.\n"); + } + } + OUTPUT_BUFFER(&MOD_REC_BUF,TEMP_OUTPUT_STREAM,1); + if (!SEEN_END_OP) + (void) fprintf(TEMP_OUTPUT_STREAM, + "eERROR[36]: End of File detected without an END statement.\n"); + + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pass1.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pass1.h:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pass1.h Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,51 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ================================ pass1.h =============================== */ + + #define START_LEGAL_1 0 /* = May see a START legally */ + #define SEEN_START_1 1 /* = Have seen a START */ + /* SEND_START_OP Global that contains whether or not */ + /* a START operator has been seen */ + extern int SEEN_START_OP; + + + #define NO_END_SEEN_1 0 /* = Haven't seen an END */ + #define END_SEEN_1 1 /* = Have seen an END but haven't */ + /* found any code after it */ + #define END_SEEN_WITH_CODE_1 2 /* = Have seen an END and code after it */ + #define START_OF_CODE_1 3 /* = Start of code */ + /* SEEN_END_OP Flag to determine if seen an end since */ + /* start of last module or not. If so it */ + /* also indicated if any code seen since */ + /* end (so only one 'code after end' error */ + /* is generated. */ + extern int SEEN_END_OP; + + /* LOCATION_EXCEEDS_MEM_SIZE Indicates if location counter is greater*/ + /* then the memory size. */ + extern int LOCATION_EXCEEDS_MEM_SIZE; + + /* -------------------------- CHANGE_LOCATION ------------------------------ */ + /* 3 parameters: */ + /* 1) int *LOCATION; The location counter */ + /* 2) int INCREMENT; How much to increment it by. */ + /* 3) FILE *OUTPUT; Where to put error messages, if need be. */ + /* LOCATION = LOCATION + INCREMENT unless this puts LOCATION past MEM_SIZE, */ + /* or if the location has already exceeded the memory size. */ + extern void CHANGE_LOCATION(); + + /* ---------------------- CAPITALIZE_STRING -------------------------------- */ + /* 1 parameter: */ + /* 1) char STR[]; String to capitalize. */ + /* Make all lower case letters in the string STR upper case letters */ + extern void CAPITALIZE_STRING(); + + /* --------------------------- PASS1 --------------------------------------- */ + /* 3 parameters: + /* 1) FILE *INPUT_FILE; Stream with the source code */ + /* 2) SYMBOL_TABLE *SYM_TABLE; The symbol table (already */ + /* initialized). */ + /* 3) FILE *TEMP_OUTPUT_STREAM; Stream for the output of Pass1 */ + /* Drives the pass1 process, letting others do the real work. */ + extern void PASS1(); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pass2.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pass2.c:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pass2.c Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,189 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================ pass2.c =================================== */ + /* Drives the pass2 process, but lets other routines do the real work. */ + #include + #include + #include "stringI.h" + #include "scan_line.h" + #include "convert.h" + #include "sym_tab.h" + #include "record.h" + #include "assem.h" + #include "constants.h" + #include "buffer.h" + #include "code.h" + + /* -------------------------- PASS2 ---------------------------------------- */ + /* Drives pass2 */ + void PASS2(FILE *INPUT_STREAM,FILE *OBJECT_STREAM,FILE *LISTING_STREAM, + SYMBOL_TABLE *SYM_TAB,int *ERROR) + { + char TAG_FIELD; /* First character to each line of */ + /* output is TAG determining what */ + /* information that line contains. */ + char *REST_OF_LINE; /* Input line minus the tag field. */ + struct SYMBOL_TABLE_ENTRY *TABLE_ENTRY; + /* Entry in symbol table for a label */ + char LABEL_NAME[LABEL_SIZE_1+1]; /* Place to store a label. */ + int ERROR_SINCE_LAST_STATEMENT /* Flag for error detection */ + = FALSE_1; + + /* --------------------------- Reset module name and NEXT_MISSING_LABEL */ + /* to their values at the start of pass1 */ + MODULE_NAME[0] = '_'; + MODULE_NAME[1] = '\0'; + RESET_MISSING_LABEL_NAME(); + + INITIALIZE_TEXT_RECORD(); + + while (!feof(INPUT_STREAM)) { + TAG_FIELD = (char) getc(INPUT_STREAM); + switch (TAG_FIELD) { + case 'p': + /* what follows is straight from the source file. Assemble it. */ + if (ERROR_SINCE_LAST_STATEMENT) (void) fprintf(LISTING_STREAM,"\n"); + ERROR_SINCE_LAST_STATEMENT = FALSE_1; + CODE(INPUT_STREAM,SYM_TAB,OBJECT_STREAM,LISTING_STREAM, + &ERROR_SINCE_LAST_STATEMENT); + (*ERROR) = ((*ERROR) || ERROR_SINCE_LAST_STATEMENT); + OUTPUT_BUFFER(&ERROR_REC_BUF,LISTING_STREAM,2); + break; + + case 'e': + /* What follows is an error message from pass1. Pass it to listing file. */ + ERROR_SINCE_LAST_STATEMENT = TRUE_1; + GET_LINE(&REST_OF_LINE,INPUT_STREAM); + (void) fprintf(LISTING_STREAM,"%s\n",REST_OF_LINE); + (*ERROR) = TRUE_1; + break; + + case 't': + { + /* What follows is a text record (do to BYTE or WORD) generated in pass1 */ + /* Handle approperiately. (i.e. Let the text record handler deal with it). */ + char TEMP_CH; + int LOCATION; + + (void) fscanf(INPUT_STREAM,"%d%c",&LOCATION,&TEMP_CH); + GET_LINE(&REST_OF_LINE,INPUT_STREAM); + if ( TEMP_CH == 'W') + ADD_TO_TEXT_RECORD(REST_OF_LINE,LOCATION,OBJECT_STREAM); + else { + char TEMP[HEX_CHAR_PER_BYTE_1+1]; + int DELTA = 0; + + for (TEMP[HEX_CHAR_PER_BYTE_1]='\0';!eoln(*REST_OF_LINE); + REST_OF_LINE+=HEX_CHAR_PER_BYTE_1) { + (void) strncpy(TEMP,REST_OF_LINE,HEX_CHAR_PER_BYTE_1); + ADD_TO_TEXT_RECORD(TEMP,(LOCATION+DELTA),OBJECT_STREAM); + DELTA ++; + } + } + } + break; + + case 'E': + /* What follows is an end record... pass it and the 'E' to the object file */ + /* After printing any text records and modification records that may be */ + /* buffered. */ + PRT_TEXT_RECORD(OBJECT_STREAM); + INITIALIZE_TEXT_RECORD(); + OUTPUT_BUFFER(&MOD_REC_BUF,OBJECT_STREAM,2); + + if (!strcmp(MAIN_ROUTINE,MODULE_NAME)) { + char ADDR[MEM_ADDR_SIZE_1/BITS_PER_HALFBYTE_1+2]; + + if (START_ADDRESS == -1) + START_ADDRESS = (*LOOK_UP_SYMBOL(MODULE_NAME,MODULE_NAME, + SYM_TAB)).LOCATION; + + NUM_TO_STR(START_ADDRESS,16,MEM_ADDR_SIZE_1/BITS_PER_HALFBYTE_1+1, + ADDR); + (void) fprintf(OBJECT_STREAM,"E%s\n",ADDR); + } else (void) fprintf(OBJECT_STREAM,"E\n"); + GET_LINE(&REST_OF_LINE,INPUT_STREAM); + break; + + case 'R': + /* What follows is a refer record. Pass it and the 'R' to the object file. */ + GET_LINE(&REST_OF_LINE,INPUT_STREAM); + (void) fprintf(OBJECT_STREAM,"%c%s\n",TAG_FIELD,REST_OF_LINE); + break; + + case 'M': + /* What follows is a modification record. Put it on the modification record */ + /* buffer. */ + GET_LINE(&REST_OF_LINE,INPUT_STREAM); + ADD_TO_END_OF_BUFFER(&MOD_REC_BUF,REST_OF_LINE); + break; + + case 'd': + { + /* What follows is a define record. Pass1 didn't know the locations, just */ + /* the names. It made sure that the the defs will fit in one record though, */ + /* so here, must just put the locations after the names as output to the */ + /* object file. */ + char TEMP[LABEL_SIZE_1+1]; + int AT; + + GET_LINE(&REST_OF_LINE,INPUT_STREAM); + (void) fprintf(OBJECT_STREAM,"D"); + + for (TEMP[LABEL_SIZE_1]='\0';!eoln(*REST_OF_LINE); + REST_OF_LINE+=LABEL_SIZE_1) { + (void) strncpy(TEMP,REST_OF_LINE,LABEL_SIZE_1); + (void) fprintf(OBJECT_STREAM,"%s",TEMP); + for (AT=LABEL_SIZE_1-1;((AT > 0) && (TEMP[AT] == ' '));AT--); + TEMP[AT+1] = '\0'; + TABLE_ENTRY = LOOK_UP_SYMBOL(MODULE_NAME,TEMP,SYM_TAB); + + if (TABLE_ENTRY == NULL) { + (void) fprintf(LISTING_STREAM, + "ERROR[41]: %s Undefined label in EXTDEF.\n", + TEMP); + (void) fprintf(OBJECT_STREAM,"000000"); + (*ERROR) = 1; + + } else if ((*TABLE_ENTRY).TYPE != RELATIVE) { + (void) fprintf(LISTING_STREAM, + "ERROR[42]: %s is wrong type. Expected LABEL, found EXTREF or CONSTANT.\n", + TEMP); + (void) fprintf(OBJECT_STREAM,"000000"); + (*ERROR) = 1; + + } else PRT_NUM( (*TABLE_ENTRY).LOCATION,16,6,OBJECT_STREAM); + } + (void) fprintf(OBJECT_STREAM,"\n"); + } + break; + + case 's': + /* what follows is a start record. Means must output a Header record to */ + /* object file. */ + GET_LINE(&REST_OF_LINE,INPUT_STREAM); + BLANK_STR(LABEL_NAME); + (void) strncpy(LABEL_NAME,REST_OF_LINE,strlen(REST_OF_LINE)); + (void) strcpy(MODULE_NAME,REST_OF_LINE); + (void) fprintf(OBJECT_STREAM,"H%s",LABEL_NAME); + TABLE_ENTRY = LOOK_UP_SYMBOL(REST_OF_LINE,REST_OF_LINE,SYM_TAB); + PRT_NUM((*TABLE_ENTRY).LOCATION,16,6,OBJECT_STREAM); + PRT_NUM((*TABLE_ENTRY).LENGTH,16,6,OBJECT_STREAM); + (void) fprintf(OBJECT_STREAM,"\n"); + break; + + default: + /* Something put out by pass1 that shouldn't be here. */ + if (!feof(INPUT_STREAM)) { + + GET_LINE(&REST_OF_LINE,INPUT_STREAM); + (void) printf( + "TEMP FILE build incorrectly. This should never happen.\n"); + (void) printf("%c%s\n",TAG_FIELD,REST_OF_LINE); + } + break; + } /* END switch (TAG_FIELD) */ + } /* END while (!feof(INPUT_STREAM)) */ + PRT_TEXT_RECORD(OBJECT_STREAM); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pass2.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pass2.h:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pass2.h Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,15 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================ pass2.h =================================== */ + /* Drives the pass2 process, but lets other routines do the real work. */ + + /* -------------------------- PASS2 ---------------------------------------- */ + /* 5 parameters: */ + /* 1) FILE *INPUT_STREAM; Input for PASS2 (NOT the source). */ + /* 2) FILE *OBJECT_STREAM; Stream for the object file. */ + /* 3) FILE *LISTING_STREAM; Stream for the listing file. */ + /* 4) SYMBOL_TABLE *SYM_TAB; Symbol table build in pass1 */ + /* 5) int *ERROR; ERROR flag. Has an error been seen. */ + /* Drives pass2 */ + extern void PASS2(); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pseudo.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pseudo.c:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pseudo.c Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,515 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================= pseudo.c ================================== */ + /* Does most of the 'real' work of pass1. Contains the routines for */ + /* processing each of the pseudo operators. */ + /* Each of the procedures have the same paramters because they are all called*/ + /* by the same invocation (by use of a function pointer). Thus may of the */ + /* procedures have parameters they never use. */ + + + #include + #include + #include "assem.h" + #include "convert.h" + #include "sym_tab.h" + #include "pass1.h" + #include "scan_line.h" + #include "record.h" + #include "buffer.h" + #include "constants.h" + #include "pseudo.h" + + /* ------------------------------- PSEUDO_BYTE ----------------------------- */ + /* Process the BYTE pseudo operator. */ + void PSEUDO_BYTE(char *LABEL_NAME,char *ARGUMENTS,int *LOCATION, + SYMBOL_TABLE *SYM_TAB,FILE *OUTPUT_STREAM) + { + char *START; /* Remember where arguments started. */ + int START_LOC; /* Where the location counter started at */ + int IS_HEX_Q; /* Is this a HEX (TRUE) or char (FALSE) */ + /* Initial value. */ + + START = ARGUMENTS; + START_LOC = *LOCATION; + + if ( (IS_HEX_Q = ( (*ARGUMENTS == 'X') && ( *(ARGUMENTS + 1) = '\'')) ) || + ( (*ARGUMENTS == 'C') && ( *(ARGUMENTS + 1) = '\'')) ) + { + int ERROR = FALSE_1; /* Has an error been found. */ + + ARGUMENTS += 2; + if (*ARGUMENTS == '\'') + (void) fprintf(OUTPUT_STREAM, + "eERROR[18]: Null hexidecimal/character constant.\n"); + else { + int SIZE = 0; + + /* ------- Step through argument till find end or string or end of constant */ + while ( (!eoln(*ARGUMENTS)) && (*ARGUMENTS != '\'')) { + if (IS_HEX_Q) ERROR = (ERROR || + (CHAR_TO_DIGIT(*ARGUMENTS,16) == -1)); + ARGUMENTS ++; + if (!ERROR) SIZE ++; + } + + if (ERROR) + (void) fprintf(OUTPUT_STREAM, + "eERROR[20]: Illegal hexidecimal.\n"); + + if (*ARGUMENTS == '\'') ARGUMENTS ++; + else { + (void) fprintf(OUTPUT_STREAM, + "eERROR[21]: Illegal hexidecimal/character constant. Missing close quote.\n"); + ERROR = TRUE_1; + } + + if ( IS_HEX_Q && ( (((int) SIZE / 2) * 2) != SIZE)) { + (void) fprintf(OUTPUT_STREAM, + "eERROR[22]: Hexidecimal number is not divisible into whole bytes.\n"); + ERROR = TRUE_1; + } + + if (!ERROR) { + if (IS_HEX_Q) + /* -------- Change location counter to reflect size of BYTE block */ + CHANGE_LOCATION(LOCATION,(int) SIZE / 2, OUTPUT_STREAM); + else CHANGE_LOCATION(LOCATION,SIZE, OUTPUT_STREAM); + + if (IS_HEX_Q) { + char TEMP; + /* -------- Output text record for BYTE block (hexidecimal) */ + TEMP = *(ARGUMENTS-1); + (*(ARGUMENTS-1)) = '\0'; + (void) fprintf(OUTPUT_STREAM,"t%dB%s\n",START_LOC,(START+2)); + (*(ARGUMENTS-1)) = TEMP; + } else { + /* -------- Output text record for BYTE block (character) */ + char *LOOP; + + (void) fprintf(OUTPUT_STREAM,"t%dB",START_LOC); + for (LOOP = START + 2; LOOP <= ARGUMENTS - 2; LOOP ++) + PRT_NUM((int) *LOOP,16,2,OUTPUT_STREAM); + (void) fprintf(OUTPUT_STREAM,"\n"); + } + } + if (!IS_BLANK_OR_TAB(*ARGUMENTS) && !eoln(*ARGUMENTS)) + (void) fprintf(OUTPUT_STREAM, + "eERROR[13]: Expected a after the operand, found %c.\n", + *ARGUMENTS); + } + } else + (void) fprintf(OUTPUT_STREAM, + "eERROR[19]: Expected hexidecimal or character constant.\n"); + } + + /* --------------------------- PSEUDO_CSECT -------------------------------- */ + /* Process the CSECT pseudo operator. */ + void PSEUDO_CSECT(char *LABEL_NAME,char *ARGUMENTS,int *LOCATION, + SYMBOL_TABLE *SYM_TAB,FILE *OUTPUT_STREAM) + { + struct SYMBOL_TABLE_ENTRY *TABLE_ENTRY; + + if (!SEEN_END_OP) { + /* --------- If haven't seen an end, then pretend you did. */ + (void) fprintf(OUTPUT_STREAM,"eERROR[27]: Section %s has no 'end'.\n", + MODULE_NAME); + OUTPUT_BUFFER(&MOD_REC_BUF,OUTPUT_STREAM,1); + LOCATION_EXCEEDS_MEM_SIZE = 0; + (void) fprintf(OUTPUT_STREAM,"E\n"); + TABLE_ENTRY = LOOK_UP_SYMBOL(MODULE_NAME,MODULE_NAME,SYM_TAB); + (*TABLE_ENTRY).LENGTH = (*LOCATION) - (*TABLE_ENTRY).LOCATION; + } + + SEEN_END_OP = NO_END_SEEN_1; + + if (!strcmp(LABEL_NAME,"")) { + (void) fprintf(OUTPUT_STREAM,"eERROR[26]: CSECT requires a label.\n"); + GET_NEXT_MISSING_LABEL(LABEL_NAME,SYM_TAB); + } + + if (LOOK_UP_SYMBOL(LABEL_NAME,LABEL_NAME,SYM_TAB) != NULL) { + (void) fprintf(OUTPUT_STREAM,"eERROR[55]: Multiply defined module name.\n"); + (void) strcpy(MODULE_NAME,LABEL_NAME); + } else { + /* --------------- Update symbol to reflect fact that LABEL_NAME is a module */ + /* name. */ + TABLE_ENTRY = LOOK_UP_SYMBOL(MODULE_NAME,LABEL_NAME,SYM_TAB); + (*TABLE_ENTRY).LOCATION = 0; + (void) strcpy( (*TABLE_ENTRY).MODULE, LABEL_NAME); + (void) strcpy(MODULE_NAME,LABEL_NAME); + + /* ---------------- Reset location counter to zero */ + (*LOCATION) = 0; + (void) fprintf(OUTPUT_STREAM,"s%s\n",MODULE_NAME); + } + } + + /* --------------------------- PSEUDO_END ---------------------------------- */ + /* Process the END pseudo operator. */ + void PSEUDO_END(char *LABEL_NAME,char *ARGUMENTS,int *LOCATION, + SYMBOL_TABLE *SYM_TAB,FILE *OUTPUT_STREAM) + { + struct SYMBOL_TABLE_ENTRY *TABLE_ENTRY; + + SEEN_END_OP = END_SEEN_1; + + if (strcmp(ARGUMENTS,"")) + { + char OPERAND_LAB[LABEL_SIZE_1+1]; + char *START; + START = ARGUMENTS; + + GET_LABEL(OPERAND_LAB,ARGUMENTS,&START,pass1); + OUTPUT_BUFFER(&ERROR_REC_BUF,OUTPUT_STREAM,1); + + if (strcmp(OPERAND_LAB,"")) { + /* ----------- End specifies a start adress. */ + struct SYMBOL_TABLE_ENTRY *TABLE_ENTRY; + + TABLE_ENTRY = LOOK_UP_SYMBOL(MAIN_ROUTINE,OPERAND_LAB,SYM_TAB); + + if (TABLE_ENTRY == NULL) + (void) fprintf(OUTPUT_STREAM,"eERROR[28]: Label %s not defined.\n", + OPERAND_LAB); + else if ((*TABLE_ENTRY).TYPE == ABSOLUTE) + (void) fprintf(OUTPUT_STREAM, + "eERROR[28]: Expected label, found constant %s.\n", + OPERAND_LAB); + else { + /* ---------------- Found an valid end statement. Clear modify buffer. */ + OUTPUT_BUFFER(&MOD_REC_BUF,OUTPUT_STREAM,1); + LOCATION_EXCEEDS_MEM_SIZE = 0; + (void) fprintf(OUTPUT_STREAM,"E\n"); + if (START_ADDRESS == -1) + START_ADDRESS = (*TABLE_ENTRY).LOCATION; + else + (void) fprintf(OUTPUT_STREAM, + "eERROR[54]: Multiple starting addresses. Using first.\n"); + } + + if (!IS_BLANK_OR_TAB(*START) && !eoln(*START) && + (START != ARGUMENTS)) + (void) fprintf(OUTPUT_STREAM, + "eERROR[13]: Expected a after the operand, found %c.\n", + *START); + } else (void) fprintf(OUTPUT_STREAM, + "eERROR[31]: Expected a Symbol, found %s.\n", + ARGUMENTS); + + } else { + /* ------------------ End doesn't specify a start address */ + /* Clear modify buffer */ + OUTPUT_BUFFER(&MOD_REC_BUF,OUTPUT_STREAM,1); + LOCATION_EXCEEDS_MEM_SIZE = 0; + (void) fprintf(OUTPUT_STREAM,"E\n"); + } + TABLE_ENTRY = LOOK_UP_SYMBOL(MODULE_NAME,MODULE_NAME,SYM_TAB); + (*TABLE_ENTRY).LENGTH = (*LOCATION) - (*TABLE_ENTRY).LOCATION; + (void) strcpy(MODULE_NAME,"_"); + (*LOCATION) = 0; + } + + /* --------------------------- PSEUDO_EQU ---------------------------------- */ + /* Process the EQU pseudo operator. */ + void PSEUDO_EQU(char *LABEL_NAME,char *ARGUMENTS,int *LOCATION, + SYMBOL_TABLE *SYM_TAB,FILE *OUTPUT_STREAM) + { + if (!strcmp(LABEL_NAME,"")) + (void) fprintf(OUTPUT_STREAM,"eERROR[23]: EQU requires a label.\n"); + else { + char *START; + struct SYMBOL_TABLE_ENTRY *TABLE_ENTRY; + int ABS_VAL = ABSOLUTE_VALUE_1; + + START = ARGUMENTS; + + TABLE_ENTRY = LOOK_UP_SYMBOL(MODULE_NAME,LABEL_NAME,SYM_TAB); + + (*TABLE_ENTRY).LOCATION = + GET_EXPRESSION(&START,MEM_ADDR_SIZE_1+1,*LOCATION,SYM_TAB,&ABS_VAL); + OUTPUT_BUFFER(&ERROR_REC_BUF,OUTPUT_STREAM,1); + (*TABLE_ENTRY).TYPE = ABSOLUTE; + + if (!IS_BLANK_OR_TAB(*START) && !eoln(*START) && + (START != ARGUMENTS)) + (void) fprintf(OUTPUT_STREAM, + "eERROR[13]: Expected a after the operand, found %c.\n", + *START); + } + + } + + /* --------------------------- PSEUDO_EXTDEF ------------------------------- */ + /* Process the EXTDEF pseudo operator. */ + void PSEUDO_EXTDEF(char *LABEL_NAME,char *ARGUMENTS,int *LOCATION, + SYMBOL_TABLE *SYM_TAB,FILE *OUTPUT_STREAM) + { + char *START; + char DEF_LAB[LABEL_SIZE_1+1]; + int ERROR = FALSE_1; + char TEMP[LABEL_SIZE_1+1]; + + if (!strcmp(ARGUMENTS,"")) + (void) fprintf(OUTPUT_STREAM,"eERROR[40]: EXTDEF requires arguments.\n"); + else { + START = ARGUMENTS; + INITIALIZE_RECORD("d",LABEL_SIZE_1*5+1); + + /* ------------------ Get the list of label names put in a record buffer */ + do { + ARGUMENTS = START; + GET_LABEL(DEF_LAB,START,&START,pass1); + OUTPUT_BUFFER(&ERROR_REC_BUF,OUTPUT_STREAM,1); + + if (!strcmp(DEF_LAB,"")) ERROR = TRUE_1; + else { + BLANK_STR(TEMP); + (void) strncpy(TEMP,DEF_LAB,strlen(DEF_LAB)); + ADD_TO_RECORD(TEMP,OUTPUT_STREAM); + } + START ++; + } while (!ERROR && ((*(START-1)) == ',')); + + /* ------------------- Output the define record */ + PRT_RECORD(OUTPUT_STREAM); + + if (!IS_BLANK_OR_TAB(*START) && !eoln(*START) && !ERROR && + (START != ARGUMENTS)) + (void) fprintf(OUTPUT_STREAM, + "eERROR[13]: Expected a after the operand, found %c.\n", + *(START-1)); + + if (ERROR == 1) + (void) fprintf(OUTPUT_STREAM, + "eERROR[39]: Invalid list of symbols. Expected symbol found %s.\n", + ARGUMENTS); + } + } + + /* --------------------------- PSEUDO_EXTREF ------------------------------- */ + /* Process the EXTREF pseudo operator. */ + void PSEUDO_EXTREF(char *LABEL_NAME,char *ARGUMENTS,int *LOCATION, + SYMBOL_TABLE *SYM_TAB,FILE *OUTPUT_STREAM) + { + char *START; + char DEF_LAB[LABEL_SIZE_1+1]; + int ERROR = FALSE_1; + char TEMP[LABEL_SIZE_1+1]; + + if (!strcmp(ARGUMENTS,"")) + (void) fprintf(OUTPUT_STREAM,"eERROR[37]: EXTREF requires arguments.\n"); + else { + START = ARGUMENTS; + INITIALIZE_RECORD("R",LABEL_SIZE_1*9+1); + + /* ----------------------------- Get the list of labels that are externally */ + /* defined. Buffer them. */ + do { + ARGUMENTS = START; + GET_LABEL(DEF_LAB,START,&START,pass1); + OUTPUT_BUFFER(&ERROR_REC_BUF,OUTPUT_STREAM,1); + if (!strcmp(DEF_LAB,"")) ERROR = 1; + else if (!INSERT_IN_SYM_TAB(MODULE_NAME,DEF_LAB,0,EXTERN_REF,SYM_TAB)) + ERROR = 2; + else { + BLANK_STR(TEMP); + (void) strncpy(TEMP,DEF_LAB,strlen(DEF_LAB)); + ADD_TO_RECORD(TEMP,OUTPUT_STREAM); + } + START ++; + } while (!ERROR && ((*(START-1)) == ',')); + + PRT_RECORD(OUTPUT_STREAM); + + if (!IS_BLANK_OR_TAB(*START) && !eoln(*START) && !ERROR && + (START != ARGUMENTS)) + (void) fprintf(OUTPUT_STREAM, + "eERROR[13]: Expected a after the operand, found %c.\n", + *(START-1)); + + if (ERROR == 1) + (void) fprintf(OUTPUT_STREAM, + "eERROR[39]: Invalid list of symbols. Expected symbol found %s.\n", + ARGUMENTS); + if (ERROR == 2) { + *(START-1) = '\0'; + (void) fprintf(OUTPUT_STREAM,"eERROR[38]: %s is already defined.\n", + ARGUMENTS); + } + + } + } + + /* --------------------------- PSEUDO_RESB --------------------------------- */ + /* Process the RESB pseudo operator. */ + void PSEUDO_RESB(char *LABEL_NAME,char *ARGUMENTS,int *LOCATION, + SYMBOL_TABLE *SYM_TAB,FILE *OUTPUT_STREAM) + { + char *START; + int ABS_VAL = ABSOLUTE_VALUE_1; + + START = ARGUMENTS; + + CHANGE_LOCATION(LOCATION, + GET_EXPRESSION(&START,MEM_ADDR_SIZE_1+1,*LOCATION,SYM_TAB,&ABS_VAL), + OUTPUT_STREAM); + OUTPUT_BUFFER(&ERROR_REC_BUF,OUTPUT_STREAM,1); + if (!IS_BLANK_OR_TAB(*START) && !eoln(*START) && + (START != ARGUMENTS)) + (void) fprintf(OUTPUT_STREAM, + "eERROR[13]: Expected a after the operand, found %c.\n", + *START); + } + + /* --------------------------- PSEUDO_RESW --------------------------------- */ + /* Process the RESW pseudo operator. */ + void PSEUDO_RESW(char *LABEL_NAME,char *ARGUMENTS,int *LOCATION, + SYMBOL_TABLE *SYM_TAB,FILE *OUTPUT_STREAM) + { + char *START; + int ABS_VAL = ABSOLUTE_VALUE_1; + + START = ARGUMENTS; + + CHANGE_LOCATION(LOCATION, + GET_EXPRESSION(&START,MEM_ADDR_SIZE_1,*LOCATION,SYM_TAB,&ABS_VAL)*3, + OUTPUT_STREAM); + OUTPUT_BUFFER(&ERROR_REC_BUF,OUTPUT_STREAM,1); + + if (!IS_BLANK_OR_TAB(*START) && !eoln(*START) && + (START != ARGUMENTS)) + (void) fprintf(OUTPUT_STREAM, + "eERROR[13]: Expected a after the operand, found %c.\n", + *START); + } + + /* --------------------------- PSEUDO_START =------------------------------- */ + /* Process the START pseudo operator. */ + void PSEUDO_START(char *LABEL_NAME,char *ARGUMENTS,int *LOCATION, + SYMBOL_TABLE *SYM_TAB,FILE *OUTPUT_STREAM) + { + struct SYMBOL_TABLE_ENTRY *TABLE_ENTRY; + int VALUE; + char *START; + + if (!SEEN_END_OP) { + (void) fprintf(OUTPUT_STREAM,"eERROR[27]: Section %s has no 'end'.\n", + MODULE_NAME); + OUTPUT_BUFFER(&MOD_REC_BUF,OUTPUT_STREAM,1); + LOCATION_EXCEEDS_MEM_SIZE = 0; + (void) fprintf(OUTPUT_STREAM,"E\n"); + TABLE_ENTRY = LOOK_UP_SYMBOL(MODULE_NAME,MODULE_NAME,SYM_TAB); + (*TABLE_ENTRY).LENGTH = (*LOCATION) - (*TABLE_ENTRY).LOCATION; + } + if (SEEN_START_OP == SEEN_START_1) + (void) fprintf(OUTPUT_STREAM, + "eERROR[32]: Multiple STARTs in this file.\n"); + + SEEN_START_OP = SEEN_START_1; + SEEN_END_OP = NO_END_SEEN_1; + + if (!strcmp(LABEL_NAME,"")) { + (void) fprintf(OUTPUT_STREAM,"eERROR[33]: START requires a label.\n"); + GET_NEXT_MISSING_LABEL(LABEL_NAME,SYM_TAB); + } + + if (LOOK_UP_SYMBOL(LABEL_NAME,LABEL_NAME,SYM_TAB) != NULL) { + (void) fprintf(OUTPUT_STREAM,"eERROR[55]: Multiply defined module name.\n"); + (void) strcpy(MODULE_NAME,LABEL_NAME); + } else { + /* --------------- Modify LABEL_NAMEs symbol table entry to reflect that it */ + /* is a module name. */ + TABLE_ENTRY = LOOK_UP_SYMBOL(MODULE_NAME,LABEL_NAME,SYM_TAB); + START = ARGUMENTS; + VALUE = GET_NUM(&START,MEM_ADDR_SIZE_1+1,10); + OUTPUT_BUFFER(&ERROR_REC_BUF,OUTPUT_STREAM,1); + + if (VALUE < 0) + (void) fprintf(OUTPUT_STREAM,"eERROR[34]: Negative starting address.\n"); + else (*TABLE_ENTRY).LOCATION = VALUE; + + if (!IS_BLANK_OR_TAB(*START) && !eoln(*START) && + (START != ARGUMENTS)) + (void) fprintf(OUTPUT_STREAM, + "eERROR[13]: Expected a after the operand, found %c.\n", + *START); + + /* ---------------- Indicate that is a module and the MAIN module. */ + (void) strcpy( (*TABLE_ENTRY).MODULE, LABEL_NAME); + (void) strcpy(MODULE_NAME,LABEL_NAME); + (void) strcpy(MAIN_ROUTINE,LABEL_NAME); + + (*LOCATION) = (*TABLE_ENTRY).LOCATION; + (void) fprintf(OUTPUT_STREAM,"s%s\n",MODULE_NAME); + } + } + + /* --------------------------- PSEUDO_WORD --------------------------------- */ + /* Process the WORD pseudo operator. */ + void PSEUDO_WORD(char *LABEL_NAME,char *ARGUMENTS,int *LOCATION, + SYMBOL_TABLE *SYM_TAB,FILE *OUTPUT_STREAM) + { + int VALUE; + char *START; + int ABS_VAL = ABSOLUTE_VALUE_1; + + START = ARGUMENTS; + + VALUE = GET_EXPRESSION(&START,BITS_PER_WORD_1,*LOCATION, + SYM_TAB,&ABS_VAL); + OUTPUT_BUFFER(&ERROR_REC_BUF,OUTPUT_STREAM,1); + + (void) fprintf(OUTPUT_STREAM,"t%dW",*LOCATION); + PRT_NUM(VALUE,16,6,OUTPUT_STREAM); + (void) fprintf(OUTPUT_STREAM,"\n"); + + CHANGE_LOCATION(LOCATION,3, OUTPUT_STREAM); + + if (!IS_BLANK_OR_TAB(*START) && !eoln(*START) && + (START != ARGUMENTS)) + (void) fprintf(OUTPUT_STREAM, + "eERROR[13]: Expected a after the operand, found %c.\n", + *START); + } + + /* ---------------------------- DO_PSEUDO ---------------------------------- */ + /* execute a pseudo function */ + void DO_PSEUDO(int WHICH_PSEUDO,char *LABEL_NAME,char *ARGUMENTS,int *LOCATION, + SYMBOL_TABLE *SYM_TAB,FILE *OUTPUT_STREAM) + { + switch (WHICH_PSEUDO) { + case PSEUDO_BYTE0: + PSEUDO_BYTE(LABEL_NAME,ARGUMENTS,LOCATION,SYM_TAB,OUTPUT_STREAM); + break; + case PSEUDO_CSECT0: + PSEUDO_CSECT(LABEL_NAME,ARGUMENTS,LOCATION,SYM_TAB,OUTPUT_STREAM); + break; + case PSEUDO_END0: + PSEUDO_END(LABEL_NAME,ARGUMENTS,LOCATION,SYM_TAB,OUTPUT_STREAM); + break; + case PSEUDO_EQU0: + PSEUDO_EQU(LABEL_NAME,ARGUMENTS,LOCATION,SYM_TAB,OUTPUT_STREAM); + break; + case PSEUDO_EXTDEF0: + PSEUDO_EXTDEF(LABEL_NAME,ARGUMENTS,LOCATION,SYM_TAB,OUTPUT_STREAM); + break; + case PSEUDO_EXTREF0: + PSEUDO_EXTREF(LABEL_NAME,ARGUMENTS,LOCATION,SYM_TAB,OUTPUT_STREAM); + break; + case PSEUDO_RESB0: + PSEUDO_RESB(LABEL_NAME,ARGUMENTS,LOCATION,SYM_TAB,OUTPUT_STREAM); + break; + case PSEUDO_RESW0: + PSEUDO_RESW(LABEL_NAME,ARGUMENTS,LOCATION,SYM_TAB,OUTPUT_STREAM); + break; + case PSEUDO_START0: + PSEUDO_START(LABEL_NAME,ARGUMENTS,LOCATION,SYM_TAB,OUTPUT_STREAM); + break; + case PSEUDO_WORD0: + PSEUDO_WORD(LABEL_NAME,ARGUMENTS,LOCATION,SYM_TAB,OUTPUT_STREAM); + break; + default: break; + } + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pseudo.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pseudo.h:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/pseudo.h Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,144 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================== pseudo.h ================================= */ + /* Does most of the 'real' work of pass1. Contains the routines for */ + /* processing each of the pseudo operators. */ + /* Each of the procedures have the same paramters because they are all called*/ + /* by the same invocation (by use of a function pointer). Thus may of the */ + /* procedures have parameters they never use. */ + + /* ------------------------------- PSEUDO_BYTE ----------------------------- */ + /* 5 parameters: */ + /* ************** LABEL_NAME not used */ + /* 1) char *LABEL_NAME; LABEL found on source line. */ + /* 2) char *ARGUMENTS; Everything after the operand in source*/ + /* 3) int *LOCATION; What location counter was when this */ + /* line of source was found. */ + /* ************** SYMB_TAB not used */ + /* 4) SYMBOL_TABLE *SYM_TAB; Symbol table */ + /* 5) FILE *OUTPUT_STREAM; Stream for the output. */ + /* Process the BYTE pseudo operator. */ + extern void PSEUDO_BYTE(); + #define PSEUDO_BYTE0 1 + + /* --------------------------- PSEUDO_CSECT -------------------------------- */ + /* 5 parameters: */ + /* 1) char *LABEL_NAME; LABEL found on source line. */ + /* ************** ARGUMENTS not used */ + /* 2) char *ARGUMENTS; Everything after the operand in source*/ + /* 3) int *LOCATION; What location counter was when this */ + /* line of source was found. */ + /* 4) SYMBOL_TABLE *SYM_TAB; Symbol table */ + /* 5) FILE *OUTPUT_STREAM; Stream for the output. */ + /* Process the CSECT pseudo operator. */ + extern void PSEUDO_CSECT(); + #define PSEUDO_CSECT0 2 + + /* --------------------------- PSEUDO_END ---------------------------------- */ + /* ************** LABEL_NAME not used */ + /* 1) char *LABEL_NAME; LABEL found on source line. */ + /* 2) char *ARGUMENTS; Everything after the operand in source*/ + /* 3) int *LOCATION; What location counter was when this */ + /* line of source was found. */ + /* 4) SYMBOL_TABLE *SYM_TAB; Symbol table */ + /* 5) FILE *OUTPUT_STREAM; Stream for the output. */ + /* Process the END pseudo operator. */ + extern void PSEUDO_END(); + #define PSEUDO_END0 3 + + /* --------------------------- PSEUDO_EQU ---------------------------------- */ + /* 1) char *LABEL_NAME; LABEL found on source line. */ + /* 2) char *ARGUMENTS; Everything after the operand in source*/ + /* 3) int *LOCATION; What location counter was when this */ + /* line of source was found. */ + /* 4) SYMBOL_TABLE *SYM_TAB; Symbol table */ + /* 5) FILE *OUTPUT_STREAM; Stream for the output. */ + /* Process the EQU pseudo operator. */ + extern void PSEUDO_EQU(); + #define PSEUDO_EQU0 4 + + /* --------------------------- PSEUDO_EXTDEF ------------------------------- */ + /* ************** LABEL_NAME not used */ + /* 1) char *LABEL_NAME; LABEL found on source line. */ + /* 2) char *ARGUMENTS; Everything after the operand in source*/ + /* ************** LOCATION not used */ + /* 3) int *LOCATION; What location counter was when this */ + /* line of source was found. */ + /* 4) SYMBOL_TABLE *SYM_TAB; Symbol table */ + /* ************** SYM_TAB not used */ + /* 5) FILE *OUTPUT_STREAM; Stream for the output. */ + /* Process the EXTDEF pseudo operator. */ + extern void PSEUDO_EXTDEF(); + #define PSEUDO_EXTDEF0 5 + + /* --------------------------- PSEUDO_EXTREF ------------------------------- */ + /* ************** LABEL_NAME not used */ + /* 1) char *LABEL_NAME; LABEL found on source line. */ + /* 2) char *ARGUMENTS; Everything after the operand in source*/ + /* ************** LOCATION not used */ + /* 3) int *LOCATION; What location counter was when this */ + /* line of source was found. */ + /* 4) SYMBOL_TABLE *SYM_TAB; Symbol table */ + /* 5) FILE *OUTPUT_STREAM; Stream for the output. */ + /* Process the EXTREF pseudo operator. */ + extern void PSEUDO_EXTREF(); + #define PSEUDO_EXTREF0 6 + + /* --------------------------- PSEUDO_RESB --------------------------------- */ + /* ************** LABEL_NAME not used */ + /* 1) char *LABEL_NAME; LABEL found on source line. */ + /* 2) char *ARGUMENTS; Everything after the operand in source*/ + /* 3) int *LOCATION; What location counter was when this */ + /* line of source was found. */ + /* 4) SYMBOL_TABLE *SYM_TAB; Symbol table */ + /* 5) FILE *OUTPUT_STREAM; Stream for the output. */ + /* Process the RESB pseudo operator. */ + extern void PSEUDO_RESB(); + #define PSEUDO_RESB0 7 + + /* --------------------------- PSEUDO_RESW --------------------------------- */ + /* ************** LABEL_NAME not used */ + /* 1) char *LABEL_NAME; LABEL found on source line. */ + /* 2) char *ARGUMENTS; Everything after the operand in source*/ + /* 3) int *LOCATION; What location counter was when this */ + /* line of source was found. */ + /* 4) SYMBOL_TABLE *SYM_TAB; Symbol table */ + /* 5) FILE *OUTPUT_STREAM; Stream for the output. */ + /* Process the RESW pseudo operator. */ + extern void PSEUDO_RESW(); + #define PSEUDO_RESW0 8 + + /* --------------------------- PSEUDO_START =------------------------------- */ + /* 1) char *LABEL_NAME; LABEL found on source line. */ + /* 2) char *ARGUMENTS; Everything after the operand in source*/ + /* 3) int *LOCATION; What location counter was when this */ + /* line of source was found. */ + /* 4) SYMBOL_TABLE *SYM_TAB; Symbol table */ + /* 5) FILE *OUTPUT_STREAM; Stream for the output. */ + /* Process the START pseudo operator. */ + extern void PSEUDO_START(); + #define PSEUDO_START0 9 + + /* --------------------------- PSEUDO_WORD --------------------------------- */ + /* ************** LABEL_NAME not used */ + /* 1) char *LABEL_NAME; LABEL found on source line. */ + /* 2) char *ARGUMENTS; Everything after the operand in source*/ + /* 3) int *LOCATION; What location counter was when this */ + /* line of source was found. */ + /* 4) SYMBOL_TABLE *SYM_TAB; Symbol table */ + /* 5) FILE *OUTPUT_STREAM; Stream for the output. */ + /* Process the WORD pseudo operator. */ + extern void PSEUDO_WORD(); + #define PSEUDO_WORD0 10 + + /* ---------------------------- DO_PSEUDO ---------------------------------- */ + /* 1) int WHICH_PSEUDO; Which pseudo func to execute. */ + /* 2) char *LABEL_NAME; LABEL found on source line. */ + /* 3) char *ARGUMENTS; Everything after the operand in source*/ + /* 4) int *LOCATION; What location counter was when this */ + /* line of source was found. */ + /* 5) SYMBOL_TABLE *SYM_TAB; Symbol table */ + /* 6) FILE *OUTPUT_STREAM; Stream for the output. */ + /* execute a pseudo function */ + extern void DO_PSEUDO(); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/record.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/record.c:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/record.c Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,145 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* =============================== record.c ================================ */ + /* This is another buffering module, but unlike buffer.c that buffers whole */ + /* lines of code and whole records, this buffers pieces of one record. A */ + /* object record has an maximal size and contains as much information on */ + /* one record as it possibly can (it tries to use 1 record instead of 2, if */ + /* possible). This routine allows other routines to say, 'This belongs in a */ + /* record, take care of it'. And it descides when to start a new record and */ + /* when not put it on the current record. */ + #include + #include + #include "convert.h" + #include "constants.h" + + /* MAX_RECORD_SIZE_1 Largest size of ANY record. */ + #define MAX_RECORD_SIZE_1 80 + + char RECORD[MAX_RECORD_SIZE_1 + 1]; /* The current record creating */ + char INIT_RECORD[MAX_RECORD_SIZE_1 + 1]; /* The intial configuration */ + int NEXT_COL; /* Where the next thing will go into*/ + /* the record. */ + int MAX_SIZE; /* The maximum size of THIS record */ + int LOCATION = 0; /* Where in SICs main memory does */ + /* this record start. Only TEXT */ + /* records. */ + + /* IS_INITIALIZED Has the record been initialized? */ + #define NOT_INIT_2 0 + #define INITIALIZED_2 1 + int IS_INITIALIZED = NOT_INIT_2; + + /* --------------------------- INITIALIZE_RECORD --------------------------- */ + /* Set up all the global variables needed to handle records. */ + void INITIALIZE_RECORD(char *VAL,int SIZE) + { + if ((SIZE > MAX_RECORD_SIZE_1) || (strlen(VAL) > SIZE) || IS_INITIALIZED) + (void) printf("INITIALIZE_RECORD called illegally.\n"); + else { + (void) strcpy(INIT_RECORD,VAL); + (void) strcpy(RECORD,VAL); + MAX_SIZE = SIZE; + NEXT_COL = strlen(RECORD); + IS_INITIALIZED = INITIALIZED_2; + } + } + + /* ------------------------- PRT_RECORD ------------------------------------ */ + /* If anything is in the record, output it. Set the record to unitialized. */ + void PRT_RECORD(FILE *OUTPUT) + { + if (!IS_INITIALIZED) + (void) printf("PRT_RECORD called illegally.\n"); + else { + if (strcmp(RECORD,INIT_RECORD)) + (void) fprintf(OUTPUT,"%s\n",RECORD); + IS_INITIALIZED = NOT_INIT_2; + } + } + + /* ------------------------- ADD_TO_RECORD --------------------------------- */ + /* Put Value into the record. If the record needs to be output put it into */ + /* stream OUTPUT. */ + void ADD_TO_RECORD(char *VAL,FILE *OUTPUT) + { + int LENGTH; /* Stores legth of the record */ + int ERROR = FALSE_1; /* Has an error been detected. */ + + if (!IS_INITIALIZED) ERROR = 1; + else + if ((NEXT_COL + (LENGTH = strlen(VAL))) > MAX_SIZE) { + /* ---------- Output current record, but VAL onto next record. */ + PRT_RECORD(OUTPUT); + INITIALIZE_RECORD(INIT_RECORD,MAX_SIZE); + if ((NEXT_COL + LENGTH) > MAX_SIZE) + ERROR = 1; + } + if (!ERROR) { + (void) strcpy(&(RECORD[NEXT_COL]),VAL); + NEXT_COL += LENGTH; + } else + (void) printf("ADD_TO_RECORD called illegally.\n"); + } + + /* --------------------- INITITIALIZE_TEXT_RECORD -------------------------- */ + /* Initialize a special type of record. A text record. */ + void INITIALIZE_TEXT_RECORD(void) + { + /* Normal record contains col. 10-69 of text record. */ + INITIALIZE_RECORD("",60); + } + + /* ---------------------- PRT_TEXT_RECORD ---------------------------------- */ + /* If anything is in the text record, output it. Set the record to */ + /* unitialized. */ + void PRT_TEXT_RECORD(FILE *OUTPUT) + { + if (!IS_INITIALIZED) + (void) printf("PRT_TEXT_RECORD called illegally.\n"); + else { + if (strcmp(RECORD,INIT_RECORD)) { + (void) fprintf(OUTPUT,"T"); + PRT_NUM(LOCATION,16,6,OUTPUT); + PRT_NUM((NEXT_COL/HEX_CHAR_PER_BYTE_1),16,2,OUTPUT); + (void) fprintf(OUTPUT,"%s\n",RECORD); + + } + IS_INITIALIZED = NOT_INIT_2; + } + } + + /* ------------------------- ADD_TO_TEXT_RECORD ---------------------------- */ + /* Put Value into the text record at SIC addres PUT_AT. If the record needs */ + /* to be output put it into stream OUTPUT. Record must be output if the */ + /* current record is full, or where the VALUE belongs isn't the next spot */ + /* on the text record. */ + void ADD_TO_TEXT_RECORD(char *VAL,int PUT_AT,FILE *OUTPUT) + { + int ERROR = FALSE_1; + int LEN; + + LEN = strlen(VAL); + + if (!IS_INITIALIZED || (LEN > MAX_SIZE)) ERROR = 1; + else { + + if (!ERROR && ((LOCATION + NEXT_COL/HEX_CHAR_PER_BYTE_1) != PUT_AT) ) { + PRT_TEXT_RECORD(OUTPUT); + LOCATION = PUT_AT; + INITIALIZE_TEXT_RECORD(); + } + + if (!ERROR && ((NEXT_COL + LEN) > MAX_SIZE) ) { + PRT_TEXT_RECORD(OUTPUT); + LOCATION += strlen(RECORD)/HEX_CHAR_PER_BYTE_1; + INITIALIZE_TEXT_RECORD(); + } + } + if (!ERROR) { + (void) strcpy(&(RECORD[NEXT_COL]),VAL); + NEXT_COL += LEN; + } else + (void) printf("ADD_TO_TEXT_RECORD called illegally.\n"); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/record.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/record.h:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/record.h Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,57 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================== record.h ================================= */ + /* This is another buffering module, but unlike buffer.c that buffers whole */ + /* lines of code and whole records, this buffers pieces of one record. A */ + /* object record has an maximal size and contains as much information on */ + /* one record as it possibly can (it tries to use 1 record instead of 2, if */ + /* possible). This routine allows other routines to say, 'This belongs in a */ + /* record, take care of it'. And it descides when to start a new record and */ + /* when not put it on the current record. */ + + /* --------------------------- INITIALIZE_RECORD --------------------------- */ + /* 2 parameters: */ + /* 1) char *VAL; Intial value/header of a record */ + /* eg. "R" for a reference record. */ + /* 2) int SIZE; Biggest this type of record can ever */ + /* get. */ + /* Set up all the global variables needed to handle records. */ + extern void INITIALIZE_RECORD(); + + /* ------------------------- PRT_RECORD ------------------------------------ */ + /* 1 parameters: */ + /* 1) FILE *OUTPUT; Stream to output the record to */ + /* If anything is in the record, output it. Set the record to unitialized. */ + extern void PRT_RECORD(); + + /* ------------------------- ADD_TO_RECORD --------------------------------- */ + /* Put Value into the record. If the record needs to be output put it into */ + /* 2 parameters: */ + /* 1) char *VAL; /* Value to add to the record */ + /* 2) FILE *OUTPUT; /* If need be, where to output the record*/ + /* stream OUTPUT. */ + + extern void ADD_TO_RECORD(); + + /* --------------------- INITITIALIZE_TEXT_RECORD -------------------------- */ + /* No parameters */ + /* Initialize a special type of record. A text record. */ + extern void INITIALIZE_TEXT_RECORD(); + + /* ---------------------- PRT_TEXT_RECORD ---------------------------------- */ + /* 1 parameter: + /* 1) FILE *OUTPUT; /* Stream to output the record to */ + /* If anything is in the text record, output it. Set the record to */ + /* unitialized. */ + extern void PRT_TEXT_RECORD(); + + /* ------------------------- ADD_TO_TEXT_RECORD ---------------------------- */ + /* 1) char *VAL; /* Value to add to text record */ + /* 2) int PUT_AT; /* Location in SIC the value will go into */ + /* 3) FILE *OUTPUT; /* If need to OUTPUT, put it into stream */ + /* Put Value into the text record at SIC addres PUT_AT. If the record needs */ + /* to be output put it into stream OUTPUT. Record must be output if the */ + /* current record is full, or where the VALUE belongs isn't the next spot */ + /* on the text record. */ + extern void ADD_TO_TEXT_RECORD(); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/scan_line.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/scan_line.c:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/scan_line.c Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,217 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ================================ scan_line.c ============================ */ + /* Contains routines for doing simple parsing of source program (eg. return */ + /* label, operator and everthing after the operator). */ + #include + #include + #include + #include + #include "stringI.h" + #include "assem.h" + #include "buffer.h" + #include "constants.h" + + /* pass_type Which pass the assembler is currently in. Used to */ + /* surpress redisplaying pass1 error messages in */ + /* pass2. */ + enum pass_type {pass1,pass2}; + + /* ----------------------------- UPPER (local) ----------------------------- */ + /* If CH is a lower case letter, return the upper case version, otherwise */ + /* Return the character. */ + char UPPER(CH) + char CH; /* Character to convert to upper case (if needed). */ + { + if ((CH >= 'a') && (CH <= 'z')) return (CH - 'a' + 'A'); + else return CH; + } + + /* ------------------------------ IS_ALPHA_NUM ----------------------------- */ + /* True if CH is a capital letter or a digit. Otherwise false. */ + int IS_ALPHA_NUM(CH) + char CH; /* Character in question. */ + { + CH = UPPER(CH); + return ( ((CH >= 'A') && (CH <= 'Z')) || ((CH >= '0') && (CH <= '9')) ); + } + + /* ------------------------------ IS_BLANK_OR_TAB -------------------------- */ + /* True if CH is a blank or a tab, otherwise false. */ + int IS_BLANK_OR_TAB(CH) + char CH; /* Character in question. */ + { + return ((CH == ' ' /* Blank */) || (CH == ' ' /* TAB */)); + } + + /* ----------------------------- eoln -------------------------------------- */ + /* true if CH is the End Of LiNe character, otherwise false. */ + int eoln(CH) + char CH; /* Character in question. */ + { + return (CH == '\0'); + } + + /* -------------------------------- GET_LABEL ------------------------------ */ + /* Get a SIC/XE Label (Letter followed by zero to seven letters or digits). */ + /* Return it in LABEL. Get it from INPUT starting from NEXT_CHAR. */ + void GET_LABEL (LABEL,INPUT,NEXT_CHAR,PASS) + char *LABEL; /* Where to put the label if found. */ + char *INPUT; /* String to get the label from. */ + enum pass_type PASS; /* pass1 = buffers error messages in ERROR_REC_BUF*/ + /* pass2 = don't buffer error messages. */ + char **NEXT_CHAR; /* where to start looking for the label in INPUT */ + { + if ((UPPER(**NEXT_CHAR) >= 'A') && (UPPER(**NEXT_CHAR) <= 'Z')) { + + /* GET LABEL */ + int LABEL_LEN = 1; + (*NEXT_CHAR) ++; + while (IS_ALPHA_NUM(**NEXT_CHAR) && (!eoln(**NEXT_CHAR))) { + LABEL_LEN ++; + (*NEXT_CHAR) ++; + }; + if (LABEL_LEN > LABEL_SIZE_1) { + if (PASS == pass1) { + char TEMP; + char *ERROR_MSG; + + TEMP = INPUT[LABEL_LEN]; + INPUT[LABEL_LEN] = '\0'; + + ERROR_MSG = (char *) malloc((unsigned int) + (80+ ((int) log10((double) LABEL_SIZE_1)) +strlen(INPUT))); + (void) sprintf(ERROR_MSG, + "eERROR[1]: Label '%s' is too long (MAX %d characters).", + INPUT,LABEL_SIZE_1); + ADD_TO_END_OF_BUFFER(&ERROR_REC_BUF,ERROR_MSG); + free(ERROR_MSG); + + INPUT[LABEL_LEN] = TEMP; + }; + /* ------------------- truncate to 8 characters. */ + LABEL_LEN = LABEL_SIZE_1; + }; + (void) strncpy(LABEL,INPUT,LABEL_LEN); + LABEL[LABEL_LEN] = '\0'; + /* End GET LABEL */ + } else { + /* ---------- Object Starting at NEXT_CHAR can not possible be a label */ + /* Return the empty string ("") */ + LABEL[0] = '\0'; + } + } + + /* ------------------------- GET_OPCODE_STR -------------------------------- */ + /* Get a SIC/XE OPERAND (string of letters, not more than 8).Return it in */ + /* OPCODE. Get it from INPUT starting from NEXT_CHAR. */ + void GET_OPCODE_STR (OPCODE,NEXT_CHAR,PASS,STREAM) + char *OPCODE; /* Where to put the opcode that was found. */ + enum pass_type PASS; /* pass1 = print error messages; pass2 = don't*/ + /* print error messages. */ + char **NEXT_CHAR; /* Where to look for the OPERAND */ + FILE *STREAM; /* Stream to output error messages to. */ + { + char *START_OF_OPCODE; + START_OF_OPCODE = *NEXT_CHAR; + if ((UPPER(**NEXT_CHAR) >= 'A') && (UPPER(**NEXT_CHAR) <= 'Z')) { + + int OP_LEN = 1; + (*NEXT_CHAR) ++; + while (((UPPER(**NEXT_CHAR) >= 'A') && (UPPER(**NEXT_CHAR) <= 'Z')) + && (!eoln(**NEXT_CHAR))) { + OP_LEN ++; + (*NEXT_CHAR) ++; + }; + if (OP_LEN > LABEL_SIZE_1) { + /* -------------- (maybe) print error message, and truncate to 8 characters. */ + if (PASS == pass1) { + char TEMP; + TEMP = START_OF_OPCODE[OP_LEN]; + START_OF_OPCODE[OP_LEN] = '\0'; + (void) fprintf(STREAM, + "eERROR[3]: OpCode field '%s' is too long. Truncating to %d charaters.\n" + ,START_OF_OPCODE,LABEL_SIZE_1); + START_OF_OPCODE[OP_LEN] = TEMP; + }; + OP_LEN = LABEL_SIZE_1; + }; + (void) strncpy(OPCODE,START_OF_OPCODE,OP_LEN); + OPCODE[OP_LEN] = '\0'; + } else { + OPCODE[0] = 0; + } + } + + /* ---------------------------- SCAN_LINE ---------------------------------- */ + /* Reads in a sourse program line and does simple parsing. */ + void SCAN_LINE (LOCATION_COUNTER,INPUT_LINE,LABEL,EXTENDED,OPERATOR, + REST,PASS,STREAM,INPUT_STREAM) + int LOCATION_COUNTER; /* SIC/XE location counter at start of line*/ + char **INPUT_LINE; /* Where to return the source line */ + char *LABEL; /* Where to return the label if one exists */ + int *EXTENDED; /* Boolean: Is there a '+' before the */ + /* operator. i.e. is this extended format*/ + char *OPERATOR; /* Where to return the operator. */ + char **REST; /* Where to return everything after the */ + /* operator. Ignoring leading white-space*/ + enum pass_type PASS; /* pass1 = do print error messages and */ + /* source; pass2 = do not print error */ + /* messages. */ + FILE *STREAM; /* Stream for outputing error messages and */ + /* the source code */ + FILE *INPUT_STREAM; /* Where to get the source line from */ + { + char *CH; + + GET_LINE(INPUT_LINE,INPUT_STREAM); + (*REST) = (*INPUT_LINE); + if (PASS == pass1) + (void) fprintf(STREAM,"p%d %s\n",LOCATION_COUNTER,*REST); + CH = *REST; + if (*CH != '.') { + /* ---------------------- Not a comment line */ + GET_LABEL(LABEL,*REST,&CH,PASS); + OUTPUT_BUFFER(&ERROR_REC_BUF,STREAM,1); + /* ---------------------- Must be white space after a operator. */ + if (!IS_BLANK_OR_TAB(*CH) && !eoln(*CH)) { + if (PASS == pass1) + (void) fprintf(STREAM, + "eERROR[2]: Illegal LABEL/OPCODE seperater('%c') expected or .\n", + *CH); + CH ++; + }; + /* ---------------------- remove white space characters */ + while (IS_BLANK_OR_TAB(*CH) && !eoln(*CH)) CH ++; + + if (*CH == '+') { + CH ++; + (*EXTENDED) = 1; + } else (*EXTENDED) = 0; + + GET_OPCODE_STR(OPERATOR,&CH,PASS,STREAM); + + if ((*EXTENDED == 1) && !strcmp(OPERATOR,"") && (PASS == pass1)) + (void) fprintf(STREAM,"eERROR[5]: Expected an OPCODE after the '+'.\n"); + + /* ---------------------- Must be white space after a label. */ + if (!IS_BLANK_OR_TAB(*CH) && !eoln(*CH)) { + if (PASS == pass1) + (void) fprintf(STREAM, + "eERROR[4]: Illegal OPCODE/OPERANDS seperater('%c') expected TAB or BLANK.\n", + *CH); + CH ++; + }; + /* ---------------------- remove white space characters */ + while (IS_BLANK_OR_TAB(*CH) && !eoln(*CH)) CH ++; + + (*REST) = CH; + } else { + /* ---------------------- comment line */ + LABEL[0] = '\0'; + (*EXTENDED) = 0; + OPERATOR[0] = '\0'; + } + } + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/scan_line.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/scan_line.h:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/scan_line.h Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,53 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* =============================== scan_line.h ============================= */ + /* Contains routines for doing simple parsing of source program (eg. return */ + /* label, operator and everthing after the operator). */ + + /* pass_type Which pass the assembler is currently in. Used to */ + /* surpress redisplaying pass1 error messages in */ + /* pass2. */ + enum pass_type {pass1,pass2}; + + /* ------------------------------ IS_BLANK_OR_TAB -------------------------- */ + /* 1 parameter: */ + /* 1) char CH; Character in question. */ + /* True if CH is a blank or a tab, otherwise false. */ + extern int IS_BLANK_OR_TAB(); + + /* ----------------------------- eoln -------------------------------------- */ + /* 1 parameter: */ + /* 1) char CH; Character in question. */ + /* true if CH is the End Of LiNe character, otherwise false. */ + extern int eoln(); + + /* -------------------------------- GET_LABEL ------------------------------ */ + /* 4 parameters: */ + /* 1) char *LABEL; Where to put the label if found. */ + /* 2) char *INPUT; String to get the label from. */ + /* 3) enum pass_type PASS; pass1 = buffers error messages in ERROR_REC_BUF*/ + /* pass2 = don't buffer error messages. */ + /* 4) char **NEXT_CHAR; where to start looking for the label in INPUT */ + /* Get a SIC/XE Label (Letter followeb by zero to seven letters or digits). */ + /* Return it in LABEL. Get it from INPUT starting from NEXT_CHAR. */ + extern void GET_LABEL(); + + /* ---------------------------- SCAN_LINE ---------------------------------- */ + /* 9 parameters: */ + /* 1) int LOCATION_COUNTER; SIC/XE location counter at start of line*/ + /* 2) char **INPUT_LINE; Where to return the source line */ + /* 3) char *LABEL; Where to return the label if one exists */ + /* 4) int *EXTENDED; Boolean: Is there a '+' before the */ + /* operator. i.e. is this extended format*/ + /* 5) char *OPERATOR; Where to return the operator. */ + /* 6) char **REST; Where to return everything after the */ + /* operator. Ignoring leading white-space*/ + /* 7) enum pass_type PASS; pass1 = do print error messages and */ + /* source; pass2 = do not print error */ + /* messages. */ + /* 8) FILE *STREAM; Stream for outputing error messages and */ + /* the source code */ + /* 9) FILE *INPUT_STREAM; Where to get the source line from */ + /* Reads in a sourse program line and does simple parsing. */ + extern void SCAN_LINE(); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/stringI.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/stringI.c:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/stringI.c Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,57 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ================================ stringI.c ============================== */ + /* Reads in one line of input gauranteeing that it will return a pointer to */ + /* the whole line, no matter how long it is (it uses CALLOC a version of */ + /* MALLOC). */ + #include + + /* CARRAGIAGE_RETURN is ascii 10 */ + #define CARRIAGE_RETURN 10 + + /* LEX_LEN_INCREMENT For long strings, number of characters to */ + /* increase the string buffer by on overflow. */ + #define LEX_LEN_INCR 128 + + char CH = ' '; /* Current input Character */ + char LEXEME[LEX_LEN_INCR+1]; /* Input String */ + + char *FRONT,*BACK; /* FRONT and BACK characters of Input String */ + unsigned LEX_LEN = LEX_LEN_INCR;/* Size of the Input String Buffer */ + + + /* ------------------------------- GETCHR ---------------------------------- */ + /* gets the next character form input file and expands buffer if needed */ + void GETCHR(FILE *STREAM) + { + /* int TEMP; */ + + /* --------- get next character */ + CH = getc(STREAM); + + /* TEMP = (int) (FRONT-BACK); */ + if ((FRONT-BACK) < ((int)LEX_LEN-3)) { + /* --------- update input string appropriately */ + FRONT ++; + *FRONT = CH; + *(FRONT+1) = '\0'; + } + } + + /* --------------------------------- GET_LINE ------------------------------ */ + /* Read in a line from the input stream. */ + void GET_LINE(char **LINE,FILE *STREAM) + { + /* -------- Clear input string */ + LEXEME[0] = '\0'; + /* -------- reset pointers */ + BACK = LEXEME; + FRONT = BACK - 1; + + GETCHR(STREAM); + while ((CH != CARRIAGE_RETURN) && !feof(STREAM)) + GETCHR(STREAM); + *FRONT = '\0'; + *LINE = LEXEME; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/stringI.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/stringI.h:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/stringI.h Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,15 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* =============================== stringI.h =============================== */ + /* Reads in one line of input gauranteeing that it will return a pointer to */ + /* the whole line, no matter how long it is (it uses CALLOC a version of */ + /* MALLOC). */ + + /* --------------------------------- GET_LINE ------------------------------ */ + /* 2 parameters: */ + /* 1) char **LINE; Points to the input line (string) when done*/ + /* 2) FILE *STREAM; Where to get the line from. */ + /* Read in a line from the input stream. */ + extern void GET_LINE(); + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/sym_tab.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/sym_tab.c:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/sym_tab.c Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,59 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ================================ sym_tab.c ============================== */ + /* intialize, retrieve from, and store to the symbol table. Currently */ + /* implemented with a linked list and linear search. */ + #include "sym_tab.h" + #include + #include + #include + + /* -------------------------------- INIT_SYM_TAB --------------------------- */ + /* Initialize the symbol table TABLE. */ + void INIT_SYM_TAB(SYMBOL_TABLE *TABLE) + { + *TABLE = NULL; + } + + /* ------------------------- LOOK_UP_SYMBOL -------------------------------- */ + /* find a symbol in the table. Return a pointer to its entry in the table, if*/ + /* found, otherwise return NULL. */ + struct SYMBOL_TABLE_ENTRY *LOOK_UP_SYMBOL(char MODULE[],char LABEL[], + SYMBOL_TABLE *TABLE) + { + struct SYMBOL_TABLE_ENTRY *TABLE_ENTRY; + TABLE_ENTRY = *TABLE; + while (TABLE_ENTRY != NULL) + { + if ( !strcmp((*TABLE_ENTRY).MODULE,MODULE) && + !strcmp((*TABLE_ENTRY).LABEL,LABEL)) return TABLE_ENTRY; + TABLE_ENTRY = (*TABLE_ENTRY).NEXT; + } + return NULL; + } + + /* -------------------------- INSERT_IN_SYM_TAB ---------------------------- */ + /* If pair is not in the symbol table, put it there and */ + /* TRUE (integer 1). Otherwise return FALSE (integer 0). */ + /* Puts onto front of the linked list. */ + int INSERT_IN_SYM_TAB(char *MODULE,char *LABEL,int LOCATION,enum kind TYPE, + SYMBOL_TABLE *TABLE) + { + struct SYMBOL_TABLE_ENTRY *TABLE_ENTRY; + + TABLE_ENTRY = LOOK_UP_SYMBOL(MODULE,LABEL,TABLE); + if (TABLE_ENTRY == NULL) + { + TABLE_ENTRY = (struct SYMBOL_TABLE_ENTRY *) malloc(sizeof(struct SYMBOL_TABLE_ENTRY)); + (*TABLE_ENTRY).NEXT = *TABLE; + (void) strcpy((*TABLE_ENTRY).MODULE, MODULE); + (void) strcpy((*TABLE_ENTRY).LABEL, LABEL); + (*TABLE_ENTRY).LOCATION = LOCATION; + (*TABLE_ENTRY).LENGTH = 0; + (*TABLE_ENTRY).TYPE = TYPE; + *TABLE = TABLE_ENTRY; + return 1; + } + else return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/sym_tab.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/sym_tab.h:1.1 *** /dev/null Tue Oct 5 13:24:30 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/assembler/sym_tab.h Tue Oct 5 13:24:16 2004 *************** *** 0 **** --- 1,54 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ========================= sym_tab.h ===================================== */ + #include "constants.h" + + /* kind What kind/type of symbol is it. */ + enum kind {RELATIVE,ABSOLUTE,EXTERN_REF,MODULE,GLOBAL,UNDEFINED}; + + /* SYMBOL_TABLE_ENTRY type of a symbol table entry. Part of a linked list*/ + typedef struct SYMBOL_TABLE_ENTRY { + char LABEL[LABEL_SIZE_1+1]; /* Name of the symbol. */ + char MODULE[LABEL_SIZE_1+1]; /* [Program] Module the symbol was found */ + /* int. */ + int LOCATION; /* Location in SICs memory this label */ + /* represents. For module names it */ + /* is the starting address. For */ + /* constants it is the value. */ + int LENGTH; /* Only for module names, the length of */ + /* the module. */ + enum kind TYPE; /* kind/type of label (relative, ...) */ + struct SYMBOL_TABLE_ENTRY *NEXT; /* Pointer to next entry in the list */ + } *SYMBOL_TABLE; + + /* -------------------------------- INIT_SYM_TAB --------------------------- */ + /* 1 parameter: */ + /* 1) SYMBOL_TABLE *TABLE; */ + /* Initialize the symbol table TABLE. */ + extern void INIT_SYM_TAB(); + + /* ------------------------- LOOK_UP_SYMBOL -------------------------------- */ + /* 3 parameters: */ + /* 1) char MODULE[]; /* Name of module label found it. */ + /* 2) char LABEL[]; /* Label to look for. */ + /* 3) SYMBOL_TABLE *TABLE; /* Table to look in. */ + /* find a symbol in the table. Return a pointer to its entry in the table, if*/ + /* found, otherwise return NULL. */ + extern struct SYMBOL_TABLE_ENTRY *LOOK_UP_SYMBOL(); + + /* -------------------------- INSERT_IN_SYM_TAB ---------------------------- */ + /* 5 parameters: */ + /* 1) char *LABEL; Label to add. */ + /* 2) char *MODULE; Module that this label was found in. */ + /* 3) int LOCATION; What the entries LOCATION field */ + /* should be set to. */ + /* 4) enum kind TYPE; What the entries TYPE field should be */ + /* set to. */ + /* 5) SYMBOL_TABLE *TABLE; Table to add to. */ + /* If pair is not in the symbol table, put it there and */ + /* TRUE (integer 1). Otherwise return FALSE (integer 0). */ + /* Puts onto front of the linked list. */ + extern int INSERT_IN_SYM_TAB(); + + From lattner at cs.uiuc.edu Tue Oct 5 13:31:44 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:31:44 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/ Message-ID: <200410051831.NAA22645@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/bison: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/bison added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 13:32:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:32:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/COPYING LR0.c Makefile allocate.c bison.1 bison.cld bison.hairy bison.simple closure.c conflicts.c derives.c files.c files.h getargs.c getopt.c gram.c gram.h lalr.c lex.c lex.h machine.h main.c new.h nullable.c output.c parse.y.in print.c reader.c state.h symtab.c symtab.h types.h warshall.c Message-ID: <200410051832.NAA22721@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/bison: COPYING added (r1.1) LR0.c added (r1.1) Makefile added (r1.1) allocate.c added (r1.1) bison.1 added (r1.1) bison.cld added (r1.1) bison.hairy added (r1.1) bison.simple added (r1.1) closure.c added (r1.1) conflicts.c added (r1.1) derives.c added (r1.1) files.c added (r1.1) files.h added (r1.1) getargs.c added (r1.1) getopt.c added (r1.1) gram.c added (r1.1) gram.h added (r1.1) lalr.c added (r1.1) lex.c added (r1.1) lex.h added (r1.1) machine.h added (r1.1) main.c added (r1.1) new.h added (r1.1) nullable.c added (r1.1) output.c added (r1.1) parse.y.in added (r1.1) print.c added (r1.1) reader.c added (r1.1) state.h added (r1.1) symtab.c added (r1.1) symtab.h added (r1.1) types.h added (r1.1) warshall.c added (r1.1) --- Log message: Initial checkin --- Diffs of the changes: (+11024 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/COPYING diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/COPYING:1.1 *** /dev/null Tue Oct 5 13:32:00 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/COPYING Tue Oct 5 13:31:49 2004 *************** *** 0 **** --- 1,141 ---- + + BISON GENERAL PUBLIC LICENSE + (Clarified 11 Feb 1988) + + Copyright (C) 1988 Richard M. Stallman + Everyone is permitted to copy and distribute verbatim copies + of this license, but changing it is not allowed. You can also + use this wording to make the terms for other programs. + + The license agreements of most software companies keep you at the + mercy of those companies. By contrast, our general public license is + intended to give everyone the right to share BISON. To make sure that + you get the rights we want you to have, we need to make restrictions + that forbid anyone to deny you these rights or to ask you to surrender + the rights. Hence this license agreement. + + Specifically, we want to make sure that you have the right to give + away copies of BISON, that you receive source code or else can get it + if you want it, that you can change BISON or use pieces of it in new + free programs, and that you know you can do these things. + + To make sure that everyone has such rights, we have to forbid you to + deprive anyone else of these rights. For example, if you distribute + copies of BISON, you must give the recipients all the rights that you + have. You must make sure that they, too, receive or can get the + source code. And you must tell them their rights. + + Also, for our own protection, we must make certain that everyone + finds out that there is no warranty for BISON. If BISON is modified by + someone else and passed on, we want its recipients to know that what + they have is not what we distributed, so that any problems introduced + by others will not reflect on our reputation. + + Therefore we (Richard Stallman and the Free Software Fundation, + Inc.) make the following terms which say what you must do to be + allowed to distribute or change BISON. + + + COPYING POLICIES + + 1. You may copy and distribute verbatim copies of BISON source code as + you receive it, in any medium, provided that you conspicuously and + appropriately publish on each copy a valid copyright notice "Copyright + (C) 1986 Free Software Foundation, Inc." (or with whatever year is + appropriate); keep intact the notices on all files that refer + to this License Agreement and to the absence of any warranty; and give + any other recipients of the BISON program a copy of this License + Agreement along with the program. + + 2. You may modify your copy or copies of BISON or any portion of it, + and copy and distribute such modifications under the terms of + Paragraph 1 above, provided that you also do the following: + + a) cause the modified files to carry prominent notices stating + that you changed the files and the date of any change; and + + b) cause the whole of any work that you distribute or publish, + that in whole or in part contains or is a derivative of BISON or + any part thereof, to be licensed at no charge to all third + parties on terms identical to those contained in this License + Agreement (except that you may choose to grant more extensive + warranty protection to some or all third parties, at your + option) + + c) You may charge a distribution fee for the physical act of + transferring a copy, and you may at your option offer warranty + protection in exchange for a fee. + + Mere aggregation of another unrelated program with this program (or its + derivative) on a volume of a storage or distribution medium does not bring + the other program under the scope of these terms. + + 3. You may copy and distribute BISON (or a portion or derivative of it, + under Paragraph 2) in object code or executable form under the terms of + Paragraphs 1 and 2 above provided that you also do one of the following: + + a) accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of + Paragraphs 1 and 2 above; or, + + b) accompany it with a written offer, valid for at least three + years, to give any third party free (except for a nominal + shipping charge) a complete machine-readable copy of the + corresponding source code, to be distributed under the terms of + Paragraphs 1 and 2 above; or, + + c) accompany it with the information you received as to where the + corresponding source code may be obtained. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form alone.) + + For an executable file, complete source code means all the source code for + all modules it contains; but, as a special exception, it need not include + source code for modules which are standard libraries that accompany the + operating system on which the executable file runs. + + 4. You may not copy, sublicense, distribute or transfer BISON + except as expressly provided under this License Agreement. Any attempt + otherwise to copy, sublicense, distribute or transfer BISON is void and + your rights to use the program under this License agreement shall be + automatically terminated. However, parties who have received computer + software programs from you with this License Agreement will not have + their licenses terminated so long as such parties remain in full compliance. + + 5. If you wish to incorporate parts of GNU CC into other free programs + whose distribution conditions are different, write to the Free Software + Foundation at 675 Mass Ave, Cambridge, MA 02139. We have not yet worked + out a simple rule that can be stated here, but we will often permit this. + We will be guided by the two goals of preserving the free status of all + derivatives of our free software and of promoting the sharing and reuse of + software. + + Your comments and suggestions about our licensing policies and our + software are welcome! Please contact the Free Software Foundation, Inc., + 675 Mass Ave, Cambridge, MA 02139, or call (617) 876-3296. + + In other words, go ahead and share BISON, but don't try to stop + anyone else from sharing it farther. Help stamp out software hoarding! + + NO WARRANTY + + BECAUSE BISON IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY NO + WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW. EXCEPT + WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC, + RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE BISON "AS IS" WITHOUT + WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND + PERFORMANCE OF BISON IS WITH YOU. SHOULD BISON PROVE DEFECTIVE, YOU + ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M. + STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY + WHO MAY MODIFY AND REDISTRIBUTE BISON AS PERMITTED ABOVE, BE LIABLE TO + YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR OTHER + SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR + INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA + BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR A + FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) BISON, EVEN + IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR + ANY CLAIM BY ANY OTHER PARTY. Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/LR0.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/LR0.c:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/LR0.c Tue Oct 5 13:31:49 2004 *************** *** 0 **** --- 1,661 ---- + /* Generate the nondeterministic finite state machine for bison, + Copyright (C) 1984, 1986 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* See comments in state.h for the data structures that represent it. + The entry point is generate_states. */ + + #include + #include "machine.h" + #include "new.h" + #include "gram.h" + #include "state.h" + + + extern char *nullable; + extern short *itemset; + extern short *itemsetend; + + + int nstates; + int final_state; + core *first_state; + shifts *first_shift; + reductions *first_reduction; + + int get_state(); + core *new_state(); + + static core *this_state; + static core *last_state; + static shifts *last_shift; + static reductions *last_reduction; + + static int nshifts; + static short *shift_symbol; + + static short *redset; + static short *shiftset; + + static short **kernel_base; + static short **kernel_end; + static short *kernel_items; + + /* hash table for states, to recognize equivalent ones. */ + + #define STATE_TABLE_SIZE 1009 + static core **state_table; + + extern void initialize_closure(int n); + extern void closure(short *core,int n); + extern void finalize_closure(void); + extern void toomany(char *s); + + void initialize_states(void); + void save_reductions(void); + void new_itemsets(void); + void append_states(void); + void save_shifts(void); + void augment_automaton(void); + void insert_start_shift(void); + + void allocate_itemsets(void) + { + register short *itemp; + register int symbol; + register int i; + register count; + register int max; + register short *symbol_count; + + count = 0; + symbol_count = NEW2(nsyms, short); + + itemp = ritem; + symbol = *itemp++; + while (symbol) + { + if (symbol > 0) + { + count++; + symbol_count[symbol]++; + } + symbol = *itemp++; + } + + /* see comments before new-itemset. All the vectors of items + live inside kernel_items. The number of active items after + some symbol cannot be more than the number of times that symbol + appears as an item, which is symbol_count[symbol]. + We allocate that much space for each symbol. */ + + kernel_base = NEW2(nsyms, short *); + kernel_items = NEW2(count, short); + + count = 0; + max = 0; + for (i = 0; i < nsyms; i++) + { + kernel_base[i] = kernel_items + count; + count += symbol_count[i]; + if (max < symbol_count[i]) + max = symbol_count[i]; + } + + shift_symbol = symbol_count; + kernel_end = NEW2(nsyms, short *); + } + + + + void allocate_storage(void) + { + allocate_itemsets(); + + shiftset = NEW2(nsyms, short); + redset = NEW2(nrules + 1, short); + state_table = NEW2(STATE_TABLE_SIZE, core *); + } + + + + void free_storage(void) + { + FREE(shift_symbol); + FREE(redset); + FREE(shiftset); + FREE(kernel_base); + FREE(kernel_end); + FREE(kernel_items); + FREE(state_table); + } + + + + /* compute the nondeterministic finite state machine (see state.h for details) + from the grammar. */ + + void generate_states(void) + { + allocate_storage(); + initialize_closure(nitems); + initialize_states(); + + while (this_state) + { + /* Set up ruleset and itemset for the transitions out of this state. + ruleset gets a 1 bit for each rule that could reduce now. + itemset gets a vector of all the items that could be accepted next. */ + closure(this_state->items, this_state->nitems); + /* record the reductions allowed out of this state */ + save_reductions(); + /* find the itemsets of the states that shifts can reach */ + new_itemsets(); + /* find or create the core structures for those states */ + append_states(); + + /* create the shifts structures for the shifts to those states, + now that the state numbers transitioning to are known */ + if (nshifts > 0) + save_shifts(); + + /* states are queued when they are created; process them all */ + this_state = this_state->next; + } + + /* discard various storage */ + finalize_closure(); + free_storage(); + + /* set up initial and final states as parser wants them */ + augment_automaton(); + } + + + + /* Find which symbols can be shifted in the current state, + and for each one record which items would be active after that shift. + Uses the contents of itemset. + shift_symbol is set to a vector of the symbols that can be shifted. + For each symbol in the grammer, kernel_base[symbol] points to + a vector of item numbers activated if that symbol is shifted, + and kernel_end[symbol] points after the end of that vector. */ + + void new_itemsets(void) + { + register int i; + register int shiftcount; + register short *isp; + register short *ksp; + register int symbol; + + #ifdef TRACE + fprintf(stderr, "Entering new_itemsets\n"); + #endif + + for (i = 0; i < nsyms; i++) + kernel_end[i] = NULL; + + shiftcount = 0; + + isp = itemset; + + while (isp < itemsetend) + { + i = *isp++; + symbol = ritem[i]; + if (symbol > 0) + { + ksp = kernel_end[symbol]; + + if (!ksp) + { + shift_symbol[shiftcount++] = symbol; + ksp = kernel_base[symbol]; + } + + *ksp++ = i + 1; + kernel_end[symbol] = ksp; + } + } + + nshifts = shiftcount; + } + + + + /* Use the information computed by new_itemset to find the state numbers + reached by each shift transition from the current state. + + shiftset is set up as a vector of state numbers of those states. */ + + void append_states(void) + { + register int i; + register int j; + register int symbol; + + #ifdef TRACE + fprintf(stderr, "Entering append_states\n"); + #endif + + /* first sort shift_symbol into increasing order */ + + for (i = 1; i < nshifts; i++) + { + symbol = shift_symbol[i]; + j = i; + while (j > 0 && shift_symbol[j - 1] > symbol) + { + shift_symbol[j] = shift_symbol[j - 1]; + j--; + } + shift_symbol[j] = symbol; + } + + for (i = 0; i < nshifts; i++) + { + symbol = shift_symbol[i]; + shiftset[i] = get_state(symbol); + } + } + + + + /* find the state number for the state we would get to + (from the current state) by shifting symbol. + Create a new state if no equivalent one exists already. + Used by append_states */ + + int get_state(int symbol) + { + register int key; + register short *isp1; + register short *isp2; + register short *iend; + register core *sp; + register int found; + + int n; + + #ifdef TRACE + fprintf(stderr, "Entering get_state, symbol = %d\n", symbol); + #endif + + isp1 = kernel_base[symbol]; + iend = kernel_end[symbol]; + n = iend - isp1; + + /* add up the target state's active item numbers to get a hash key */ + key = 0; + while (isp1 < iend) + key += *isp1++; + + key = key % STATE_TABLE_SIZE; + + sp = state_table[key]; + + if (sp) + { + found = 0; + while (!found) + { + if (sp->nitems == n) + { + found = 1; + isp1 = kernel_base[symbol]; + isp2 = sp->items; + + while (found && isp1 < iend) + { + if (*isp1++ != *isp2++) + found = 0; + } + } + + if (!found) + { + if (sp->link) + { + sp = sp->link; + } + else /* bucket exhausted and no match */ + { + sp = sp->link = new_state(symbol); + found = 1; + } + } + } + } + else /* bucket is empty */ + { + state_table[key] = sp = new_state(symbol); + } + + return (sp->number); + } + + + + /* subroutine of get_state. create a new state for those items, if necessary. */ + + core *new_state(int symbol) + { + register int n; + register core *p; + register short *isp1; + register short *isp2; + register short *iend; + + #ifdef TRACE + fprintf(stderr, "Entering new_state, symbol = %d\n", symbol); + #endif + + if (nstates >= MAXSHORT) + toomany("states"); + + isp1 = kernel_base[symbol]; + iend = kernel_end[symbol]; + n = iend - isp1; + + p = (core *) mallocate((unsigned) (sizeof(core) + (n - 1) * sizeof(short))); + p->accessing_symbol = symbol; + p->number = nstates; + p->nitems = n; + + isp2 = p->items; + while (isp1 < iend) + *isp2++ = *isp1++; + + last_state->next = p; + last_state = p; + + nstates++; + + return (p); + } + + + + void initialize_states(void) + { + register core *p; + /* register unsigned *rp1; JF unused */ + /* register unsigned *rp2; JF unused */ + /* register unsigned *rend; JF unused */ + + p = (core *) mallocate((unsigned) (sizeof(core) - sizeof(short))); + first_state = last_state = this_state = p; + nstates = 1; + } + + + + void save_shifts(void) + { + register shifts *p; + register short *sp1; + register short *sp2; + register short *send; + + p = (shifts *) mallocate((unsigned) (sizeof(shifts) + + (nshifts - 1) * sizeof(short))); + + p->number = this_state->number; + p->nshifts = nshifts; + + sp1 = shiftset; + sp2 = p->shifts; + send = shiftset + nshifts; + + while (sp1 < send) + *sp2++ = *sp1++; + + if (last_shift) + { + last_shift->next = p; + last_shift = p; + } + else + { + first_shift = p; + last_shift = p; + } + } + + + + /* find which rules can be used for reduction transitions from the current state + and make a reductions structure for the state to record their rule numbers. */ + + void save_reductions(void) + { + register short *isp; + register short *rp1; + register short *rp2; + register int item; + register int count; + register reductions *p; + + short *rend; + + /* find and count the active items that represent ends of rules */ + + count = 0; + for (isp = itemset; isp < itemsetend; isp++) + { + item = ritem[*isp]; + if (item < 0) + { + redset[count++] = -item; + } + } + + /* make a reductions structure and copy the data into it. */ + + if (count) + { + p = (reductions *) mallocate((unsigned) (sizeof(reductions) + + (count - 1) * sizeof(short))); + + p->number = this_state->number; + p->nreds = count; + + rp1 = redset; + rp2 = p->rules; + rend = rp1 + count; + + while (rp1 < rend) + *rp2++ = *rp1++; + + if (last_reduction) + { + last_reduction->next = p; + last_reduction = p; + } + else + { + first_reduction = p; + last_reduction = p; + } + } + } + + + + /* Make sure that the initial state has a shift that accepts the + grammar's start symbol and goes to the next-to-final state, + which has a shift going to the final state, which has a shift + to the termination state. + Create such states and shifts if they don't happen to exist already. */ + + void augment_automaton(void) + { + register int i; + register int k; + /* register int found; JF unused */ + register core *statep; + register shifts *sp; + register shifts *sp2; + register shifts *sp1; + + sp = first_shift; + + if (sp) + { + if (sp->number == 0) + { + k = sp->nshifts; + statep = first_state->next; + + while (statep->accessing_symbol < start_symbol + && statep->number < k) + statep = statep->next; + + if (statep->accessing_symbol == start_symbol) + { + k = statep->number; + + while (sp->number < k) + { + sp1 = sp; + sp = sp->next; + } + + if (sp->number == k) + { + sp2 = (shifts *) mallocate((unsigned) (sizeof(shifts) + + sp->nshifts * sizeof(short))); + sp2->next = sp->next; + sp2->number = k; + sp2->nshifts = sp->nshifts + 1; + sp2->shifts[0] = nstates; + for (i = sp->nshifts; i > 0; i--) + sp2->shifts[i] = sp->shifts[i - 1]; + + sp1->next = sp2; + FREE(sp); + } + else + { + sp2 = NEW(shifts); + sp2->next = sp; + sp2->number = k; + sp2->nshifts = 1; + sp2->shifts[0] = nstates; + + sp1->next = sp2; + if (!sp) + last_shift = sp2; + } + } + else + { + k = statep->number; + sp = first_shift; + + sp2 = (shifts *) mallocate((unsigned) (sizeof(shifts) + + sp->nshifts * sizeof(short))); + sp2->next = sp->next; + sp2->nshifts = sp->nshifts + 1; + + for (i = 0; i < k; i++) + sp2->shifts[i] = sp->shifts[i]; + + sp2->shifts[k] = nstates; + + for (i = k; i < sp->nshifts; i++) + sp2->shifts[i + 1] = sp->shifts[i]; + + first_shift = sp2; + if (last_shift == sp) + last_shift = sp2; + + FREE(sp); + + insert_start_shift(); + } + } + else + { + sp = NEW(shifts); + sp->next = first_shift; + sp->nshifts = 1; + sp->shifts[0] = nstates; + + first_shift = sp; + + insert_start_shift(); + } + } + else + { + sp = NEW(shifts); + sp->nshifts = 1; + sp->shifts[0] = nstates; + + first_shift = sp; + last_shift = sp; + + insert_start_shift(); + } + + statep = (core *) mallocate((unsigned) (sizeof(core) - sizeof(short))); + statep->number = nstates; + last_state->next = statep; + last_state = statep; + + sp = NEW(shifts); + sp->number = nstates++; + sp->nshifts = 1; + sp->shifts[0] = nstates; + last_shift->next = sp; + last_shift = sp; + + final_state = nstates; + + statep = (core *) mallocate((unsigned) (sizeof(core) - sizeof(short))); + statep->number = nstates++; + last_state->next = statep; + last_state = statep; + } + + + /* subroutine of augment_automaton */ + + void insert_start_shift(void) + { + register core *statep; + register shifts *sp; + + statep = (core *) mallocate((unsigned) (sizeof(core) - sizeof(short))); + statep->number = nstates; + statep->accessing_symbol = start_symbol; + + last_state->next = statep; + last_state = statep; + + sp = NEW(shifts); + sp->number = nstates++; + sp->nshifts = 1; + sp->shifts[0] = nstates; + + last_shift->next = sp; + last_shift = sp; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/Makefile:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/Makefile Tue Oct 5 13:31:49 2004 *************** *** 0 **** --- 1,5 ---- + LEVEL = ../../../.. + + PROG = mybison + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/allocate.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/allocate.c:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/allocate.c Tue Oct 5 13:31:49 2004 *************** *** 0 **** --- 1,38 ---- + /* Allocate and clear storage for bison, + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + #include + #include + + extern void done(int k); + + char *mallocate(register unsigned n) + { + register char *block; + + block = calloc(n,1); + if (block == NULL) + { + fprintf(stderr, "bison: memory exhausted\n"); + done(1); + } + + return (block); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/bison.1 diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/bison.1:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/bison.1 Tue Oct 5 13:31:49 2004 *************** *** 0 **** --- 1,96 ---- + .TH BISON 1 local + .SH NAME + bison \- GNU Project parser generator (yacc replacement) + .SH SYNOPSIS + .B bison + [ + .B \-dlvty + ] file + .SH DESCRIPTION + .I Bison + is a parser generator in the style of + .IR yacc (1). + It should be upwardly compatible with input files designed + for + .IR yacc . + .PP + Input files should follow the + .I yacc + convention of ending in ``.y''. + Unlike + .IR yacc , + the generated files do not have fixed names, but instead use the prefix + of the input file. + For instance, a grammar description file named + .B parse.y + would produce the generated parser in a file named + .BR parse.tab.c , + instead of + .IR yacc 's + .BR y.tab.c . + .PP + .I Bison + takes five optional flags. + .TP + .B \-d + Produce a + .B .tab.h + file, similar to + .IR yacc 's + .B y.tab.h + file. + .TP + .B \-l + Omit + .B #line + lines in the parser output file. Error messages from the C compiler will + then be associated with lines in the parser output file, instead of lines + in the original grammar file. + .TP + .B \-t + Turn on debugging. This option causes the + .I bison + output to have debugging code made available via the C pre-processor. + The external variable + .B yydebug + should be made non-zero to have the debugging code actually + produce output. + .TP + .B \-v + Be verbose. Analogous to the same flag for + .IR yacc . + .TP + .B \-y + Use fixed output file names. I.e., force the output to be in files + .BR y.tab.c , + .BR y.tab.h , + and so on. This is for full + .I yacc + compatibility. + .PP + If + .I bison + is invoked with the name + .IR yacc , + it will behave like + .I yacc + does. This is equivalent to simply supplying the + .B \-y + flag. + .SH FILES + /usr/local/lib/bison.simple simple parser + .br + /usr/local/lib/bison.hairy complicated parser + .SH SEE ALSO + .IR yacc (1) + .br + The + .IR "Bison Reference Manual" , + included as the file + .B bison.texinfo + in the + .I bison + source distribution. + .SH DIAGNOSTICS + ``Self explanatory.'' + ... ha! Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/bison.cld diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/bison.cld:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/bison.cld Tue Oct 5 13:31:49 2004 *************** *** 0 **** --- 1,11 ---- + ! + ! VMS BISON command definition file + ! + DEFINE VERB BISON + IMAGE GNU_BISON:[000000]BISON + + PARAMETER P1,Label=BISON$INFILE,Prompt="File" + value(required,type=$infile) + QUALIFIER VERBOSE,Label=BISON$VERBOSE + QUALIFIER DEFINES,Label=BISON$DEFINES + QUALIFIER FIXED_OUTFILES,Label=BISON$FIXED_OUTFILES Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/bison.hairy diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/bison.hairy:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/bison.hairy Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,334 ---- + + extern int timeclock; + + + int yyerror; /* Yyerror and yycost are set by guards. */ + int yycost; /* If yyerror is set to a nonzero value by a */ + /* guard, the reduction with which the guard */ + /* is associated is not performed, and the */ + /* error recovery mechanism is invoked. */ + /* Yycost indicates the cost of performing */ + /* the reduction given the attributes of the */ + /* symbols. */ + + + /* YYMAXDEPTH indicates the size of the parser's state and value */ + /* stacks. */ + + #ifndef YYMAXDEPTH + #define YYMAXDEPTH 500 + #endif + + /* YYMAXRULES must be at least as large as the number of rules that */ + /* could be placed in the rule queue. That number could be determined */ + /* from the grammar and the size of the stack, but, as yet, it is not. */ + + #ifndef YYMAXRULES + #define YYMAXRULES 100 + #endif + + #ifndef YYMAXBACKUP + #define YYMAXBACKUP 100 + #endif + + + short yyss[YYMAXDEPTH]; /* the state stack */ + YYSTYPE yyvs[YYMAXDEPTH]; /* the semantic value stack */ + YYLTYPE yyls[YYMAXDEPTH]; /* the location stack */ + short yyrq[YYMAXRULES]; /* the rule queue */ + int yychar; /* the lookahead symbol */ + + YYSTYPE yylval; /* the semantic value of the */ + /* lookahead symbol */ + + YYSTYPE yytval; /* the semantic value for the state */ + /* at the top of the state stack. */ + + YYSTYPE yyval; /* the variable used to return */ + /* semantic values from the action */ + /* routines */ + + YYLTYPE yylloc; /* location data for the lookahead */ + /* symbol */ + + YYLTYPE yytloc; /* location data for the state at the */ + /* top of the state stack */ + + + int yynunlexed; + short yyunchar[YYMAXBACKUP]; + YYSTYPE yyunval[YYMAXBACKUP]; + YYLTYPE yyunloc[YYMAXBACKUP]; + + short *yygssp; /* a pointer to the top of the state */ + /* stack; only set during error */ + /* recovery. */ + + YYSTYPE *yygvsp; /* a pointer to the top of the value */ + /* stack; only set during error */ + /* recovery. */ + + YYLTYPE *yyglsp; /* a pointer to the top of the */ + /* location stack; only set during */ + /* error recovery. */ + + + /* Yyget is an interface between the parser and the lexical analyzer. */ + /* It is costly to provide such an interface, but it avoids requiring */ + /* the lexical analyzer to be able to back up the scan. */ + + yyget() + { + if (yynunlexed > 0) + { + yynunlexed--; + yychar = yyunchar[yynunlexed]; + yylval = yyunval[yynunlexed]; + yylloc = yyunloc[yynunlexed]; + } + else if (yychar <= 0) + yychar = 0; + else + { + yychar = yylex(); + if (yychar < 0) + yychar = 0; + else yychar = YYTRANSLATE(yychar); + } + } + + + + yyunlex(chr, val, loc) + int chr; + YYSTYPE val; + YYLTYPE loc; + { + yyunchar[yynunlexed] = chr; + yyunval[yynunlexed] = val; + yyunloc[yynunlexed] = loc; + yynunlexed++; + } + + + + yyrestore(first, last) + register short *first; + register short *last; + { + register short *ssp; + register short *rp; + register int symbol; + register int state; + register int tvalsaved; + + ssp = yygssp; + yyunlex(yychar, yylval, yylloc); + + tvalsaved = 0; + while (first != last) + { + symbol = yystos[*ssp]; + if (symbol < YYNTBASE) + { + yyunlex(symbol, yytval, yytloc); + tvalsaved = 1; + ssp--; + } + + ssp--; + + if (first == yyrq) + first = yyrq + YYMAXRULES; + + first--; + + for (rp = yyrhs + yyprhs[*first]; symbol = *rp; rp++) + { + if (symbol < YYNTBASE) + state = yytable[yypact[*ssp] + symbol]; + else + { + state = yypgoto[symbol - YYNTBASE] + *ssp; + + if (state >= 0 && state <= YYLAST && yycheck[state] == *ssp) + state = yytable[state]; + else + state = yydefgoto[symbol - YYNTBASE]; + } + + *++ssp = state; + } + } + + if ( ! tvalsaved && ssp > yyss) + { + yyunlex(yystos[*ssp], yytval, yytloc); + ssp--; + } + + yygssp = ssp; + } + + + + int + yyparse() + { + register int yystate; + register int yyn; + register short *yyssp; + register short *yyrq0; + register short *yyptr; + register YYSTYPE *yyvsp; + + int yylen; + YYLTYPE *yylsp; + short *yyrq1; + short *yyrq2; + + yystate = 0; + yyssp = yyss - 1; + yyvsp = yyvs - 1; + yylsp = yyls - 1; + yyrq0 = yyrq; + yyrq1 = yyrq0; + yyrq2 = yyrq0; + + yychar = yylex(); + if (yychar < 0) + yychar = 0; + else yychar = YYTRANSLATE(yychar); + + yynewstate: + + if (yyssp >= yyss + YYMAXDEPTH - 1) + { + yyabort("Parser Stack Overflow"); + YYABORT; + } + + *++yyssp = yystate; + + yyresume: + + yyn = yypact[yystate]; + if (yyn == YYFLAG) + goto yydefault; + + yyn += yychar; + if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != yychar) + goto yydefault; + + yyn = yytable[yyn]; + if (yyn < 0) + { + yyn = -yyn; + goto yyreduce; + } + else if (yyn == 0) + goto yyerrlab; + + yystate = yyn; + + yyptr = yyrq2; + while (yyptr != yyrq1) + { + yyn = *yyptr++; + yylen = yyr2[yyn]; + yyvsp -= yylen; + yylsp -= yylen; + + yyguard(yyn, yyvsp, yylsp); + if (yyerror) + goto yysemerr; + + yyaction(yyn, yyvsp, yylsp); + *++yyvsp = yyval; + + yylsp++; + if (yylen == 0) + { + yylsp->timestamp = timeclock; + yylsp->first_line = yytloc.first_line; + yylsp->first_column = yytloc.first_column; + yylsp->last_line = (yylsp-1)->last_line; + yylsp->last_column = (yylsp-1)->last_column; + yylsp->text = 0; + } + else + { + yylsp->last_line = (yylsp+yylen-1)->last_line; + yylsp->last_column = (yylsp+yylen-1)->last_column; + } + + if (yyptr == yyrq + YYMAXRULES) + yyptr = yyrq; + } + + if (yystate == YYFINAL) + YYACCEPT; + + yyrq2 = yyptr; + yyrq1 = yyrq0; + + *++yyvsp = yytval; + *++yylsp = yytloc; + yytval = yylval; + yytloc = yylloc; + yyget(); + + goto yynewstate; + + yydefault: + + yyn = yydefact[yystate]; + if (yyn == 0) + goto yyerrlab; + + yyreduce: + + *yyrq0++ = yyn; + + if (yyrq0 == yyrq + YYMAXRULES) + yyrq0 = yyrq; + + if (yyrq0 == yyrq2) + { + yyabort("Parser Rule Queue Overflow"); + YYABORT; + } + + yyssp -= yyr2[yyn]; + yyn = yyr1[yyn]; + + yystate = yypgoto[yyn - YYNTBASE] + *yyssp; + if (yystate >= 0 && yystate <= YYLAST && yycheck[yystate] == *yyssp) + yystate = yytable[yystate]; + else + yystate = yydefgoto[yyn - YYNTBASE]; + + goto yynewstate; + + yysemerr: + *--yyptr = yyn; + yyrq2 = yyptr; + yyvsp += yyr2[yyn]; + + yyerrlab: + + yygssp = yyssp; + yygvsp = yyvsp; + yyglsp = yylsp; + yyrestore(yyrq0, yyrq2); + yyrecover(); + yystate = *yygssp; + yyssp = yygssp; + yyvsp = yygvsp; + yyrq0 = yyrq; + yyrq1 = yyrq0; + yyrq2 = yyrq0; + goto yyresume; + } + + $ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/bison.simple diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/bison.simple:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/bison.simple Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,1371 ---- + #line 2 "bison.simple" + /* Skeleton output parser for bison, + copyright (C) 1984 Bob Corbett and Richard Stallman + + NO WARRANTY + + BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY + NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW. EXCEPT + WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC, + RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS" + WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY + AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE + DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR + CORRECTION. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M. + STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY + WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE + LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR + OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE + USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR + DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR + A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS + PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH + DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY. + + GENERAL PUBLIC LICENSE TO COPY + + 1. You may copy and distribute verbatim copies of this source file + as you receive it, in any medium, provided that you conspicuously and + appropriately publish on each copy a valid copyright notice "Copyright + (C) 1985 Free Software Foundation, Inc."; and include following the + copyright notice a verbatim copy of the above disclaimer of warranty + and of this License. You may charge a distribution fee for the + physical act of transferring a copy. + + 2. You may modify your copy or copies of this source file or + any portion of it, and copy and distribute such modifications under + the terms of Paragraph 1 above, provided that you also do the following: + + a) cause the modified files to carry prominent notices stating + that you changed the files and the date of any change; and + + b) cause the whole of any work that you distribute or publish, + that in whole or in part contains or is a derivative of this + program or any part thereof, to be licensed at no charge to all + third parties on terms identical to those contained in this + License Agreement (except that you may choose to grant more extensive + warranty protection to some or all third parties, at your option). + + c) You may charge a distribution fee for the physical act of + transferring a copy, and you may at your option offer warranty + protection in exchange for a fee. + + Mere aggregation of another unrelated program with this program (or its + derivative) on a volume of a storage or distribution medium does not bring + the other program under the scope of these terms. + + 3. You may copy and distribute this program (or a portion or derivative + of it, under Paragraph 2) in object code or executable form under the terms + of Paragraphs 1 and 2 above provided that you also do one of the following: + + a) accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of + Paragraphs 1 and 2 above; or, + + b) accompany it with a written offer, valid for at least three + years, to give any third party free (except for a nominal + shipping charge) a complete machine-readable copy of the + corresponding source code, to be distributed under the terms of + Paragraphs 1 and 2 above; or, + + c) accompany it with the information you received as to where the + corresponding source code may be obtained. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form alone.) + + For an executable file, complete source code means all the source code for + all modules it contains; but, as a special exception, it need not include + source code for modules which are standard libraries that accompany the + operating system on which the executable file runs. + + 4. You may not copy, sublicense, distribute or transfer this program + except as expressly provided under this License Agreement. Any attempt + otherwise to copy, sublicense, distribute or transfer this program is void and + your rights to use the program under this License agreement shall be + automatically terminated. However, parties who have received computer + software programs from you with this License Agreement will not have + their licenses terminated so long as such parties remain in full compliance. + + 5. If you wish to incorporate parts of this program into other free + programs whose distribution conditions are different, write to the Free + Software Foundation at 675 Mass Ave, Cambridge, MA 02139. We have not yet + worked out a simple rule that can be stated here, but we will often permit + this. We will be guided by the two goals of preserving the free status of + all derivatives of our free software and of promoting the sharing and reuse of + software. + + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* This is the parser code that is written into each bison parser + when the %semantic_parser declaration is not specified in the grammar. + It was written by Richard Stallman by simplifying the hairy parser + used when %semantic_parser is specified. */ + + /* Note: there must be only one dollar sign in this file. + It is replaced by the list of actions, each action + as one case of the switch. */ + + #define yyerrok (yyp->yyerrstatus = 0) + #define yyclearin (yychar = YYEMPTY) + #define YYEMPTY -2 + #define YYEOF 0 + #define YYFAIL goto yyerrlab; + #define YYACCEPT goto yyaccept + #define YYABORT goto yyabort + + #define YYTERROR 1 + + #ifndef YYIMPURE + #define YYLEX yylex(currentfile) + #endif + + static char *dummy = NULL; + char **_yytext = &dummy; + static YYSTYPE dummys; + YYSTYPE *_yylval = &dummys; + static YYLTYPE dummyl; + YYLTYPE *_yylloc = &dummyl; + static int dummyp; + int *_yyppval = &dummyp; + + #ifdef YYDEBUG + int yydebug = 0; /* nonzero means print parse debug info */ + int yytrace = 0; /* nonzero means print high-level parse + trace */ + #endif + + #ifndef YYPURE + #define YYLEX yylex(currentfile, &yylval, &yylloc) + #endif + + /* If nonreentrant, generate the variables here */ + + #ifndef YYIMPURE + + int yyn; + + #endif /* YYIMPURE */ + + + /* YYMAXDEPTH indicates the initial size of the parser's stacks */ + + #ifndef YYMAXDEPTH + #define YYMAXDEPTH 200 + #endif + + /* YYMAXLIMIT is the maximum size the stacks can grow to + (effective only if the built-in stack extension method is used). */ + + #ifndef YYMAXLIMIT + #define YYMAXLIMIT 10000 + #endif + + #define YYMAXFORKDEPTH 20 + + typedef struct parsestate { + struct parsestate *flink, *blink; + char *text; + YYSTYPE lval; + YYLTYPE lloc; + int cur_token_number; + int yychar; + int blocked; + int lineno; /* line number containing PP token */ + int yystate; + int yyerrstatus; + int yynerr; /* number of parse errors so far */ + short *yyss, *yyssp; /* state stack and state tos */ + YYSTYPE *yyvs, *yyvsp, *last_reduction; /* val stack and val tos */ + YYSTYPE *tos_stack[YYMAXFORKDEPTH], **tos_tos; + #ifdef YYLSP_NEEDED + YYLTYPE *yyls, *yylsp; /* line stack and line tos */ + #endif + unsigned short flags_stack[YYMAXFORKDEPTH], *flags; /* control flags */ + int data_stack[YYMAXFORKDEPTH], *data; /* client specific data */ + /* The following manage the correspondence between the + two parses for an #ifdef. "pending_join" is the + partner that will be next joined to. "pending_endif" + is the partner that will be awoken on the next ifdef. */ + struct parsestate *pending_join_stack[YYMAXFORKDEPTH], **pending_join; + struct parsestate *pending_endif_stack[YYMAXFORKDEPTH], **pending_endif; + short yymaxdepth; /* max depth of current stack */ + #ifdef YYDEBUG + char *branch_stack[YYMAXFORKDEPTH], **branch; + #endif + } *parse; + + #define SEEN_ENDIF_BIT 0x01 + #define SEEN_PP_TOKEN_BIT 0x02 + #define JOIN_PENDING_BIT 0x04 + #define IFDEF_FORK_BIT 0x08 + #define JUST_SHIFTED_BIT 0x10 + #define ACCEPTED_BIT 0x20 + #define ABORTED_BIT 0x40 + #define ACTIVE_BIT 0x80 + #define DONE_SOMETHING_BIT 0x100 + #define SEEN_ENDIF(p) (*(p)->flags & SEEN_ENDIF_BIT) + #define SEEN_PP_TOKEN(p) (*(p)->flags & SEEN_PP_TOKEN_BIT) + #define JOIN_PENDING(p) (*(p)->flags & JOIN_PENDING_BIT) + #define IFDEF_FORK(p) (*(p)->flags & IFDEF_FORK_BIT) + #define JUST_SHIFTED(p) (*(p)->flags & JUST_SHIFTED_BIT) + #define ACCEPTED(p) (*(p)->flags & ACCEPTED_BIT) + #define ABORTED(p) (*(p)->flags & ABORTED_BIT) + #define ACTIVE(p) (*(p)->flags & ACTIVE_BIT) + #define DONE_SOMETHING(p) (*(p)->flags & DONE_SOMETHING_BIT) + #define SET_SEEN_ENDIF(p) (*(p)->flags |= SEEN_ENDIF_BIT) + #define SET_SEEN_PP_TOKEN(p) (*(p)->flags |= SEEN_PP_TOKEN_BIT) + #define SET_JOIN_PENDING(p) (*(p)->flags |= JOIN_PENDING_BIT) + #define SET_IFDEF_FORK(p) (*(p)->flags |= IFDEF_FORK_BIT) + #define SET_JUST_SHIFTED(p) (*(p)->flags |= JUST_SHIFTED_BIT) + #define SET_ACCEPTED(p) (*(p)->flags |= ACCEPTED_BIT) + #define SET_ABORTED(p) (*(p)->flags |= ABORTED_BIT) + #define SET_ACTIVE(p) (*(p)->flags |= ACTIVE_BIT) + #define SET_DONE_SOMETHING(p) (*(p)->flags |= DONE_SOMETHING_BIT) + #define UNSET_SEEN_ENDIF(p) (*(p)->flags &= ~SEEN_ENDIF_BIT) + #define UNSET_SEEN_PP_TOKEN(p) (*(p)->flags &= ~SEEN_PP_TOKEN_BIT) + #define UNSET_JOIN_PENDING(p) (*(p)->flags &= ~JOIN_PENDING_BIT) + #define UNSET_IFDEF_FORK(p) (*(p)->flags &= ~IFDEF_FORK_BIT) + #define UNSET_JUST_SHIFTED(p) (*(p)->flags &= ~JUST_SHIFTED_BIT) + #define UNSET_ACCEPTED(p) (*(p)->flags &= ~ACCEPTED_BIT) + #define UNSET_ABORTED(p) (*(p)->flags &= ~ABORTED_BIT) + #define UNSET_ACTIVE(p) (*(p)->flags &= ~ACTIVE_BIT) + #define UNSET_DONE_SOMETHING(p) (*(p)->flags &= ~DONE_SOMETHING_BIT) + #define UNSET_ALL(p) (*(p)->flags = 0) + + #ifdef YYDEBUG + void + dumpparse(p) + parse p; + { + short *ss; + + printf("parse %x, flink=%x, blink=%x, token=%d, yychar=%d\n", + p, p->flink, p->blink, p->cur_token_number, p->yychar); + printf("\tblocked=%d, lineno=%d, yystate=%d, yyerrstatus=%d, yynerr=%d\n", + p->blocked, p->lineno, p->yystate, p->yyerrstatus, p->yynerr); + printf("\tstate-stack: "); + for (ss = p->yyss; ss <= p->yyssp; ss++) { + printf(" %d", *ss); + if (ss - p->yyss == *p->tos_tos - p->yyvs) + printf(" t"); + } + printf("\n\n"); + } + + #endif + + #if 0 + extern int yylineno(); /* current line number per the scanner */ + #endif + + int id; + + YYSTYPE (*yyfork)(); + YYSTYPE (*yyjoin)(); + void (*yyelse)(); + void (*yyendif)(); + void (*yyfinish)(); + void (*yyswitch)(); + int (*yyskip)(); + + #include "preprocessor.h" + #include "alloc.h" + + extern FILE *errfile; + + parse + start_parse() + { + register parse p; + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Starting parse\n"); + #endif + p = (parse)Malloc(sizeof *p); + + p->yystate = 0; + p->yyerrstatus = 0; + p->yynerr = 0; + p->blocked = 0; + p->cur_token_number = -1; + p->yychar = YYEMPTY; + p->last_reduction = 0; + + /* Initialize stack pointers. Waste one element of value and + * location stack so that they stay on the same level as the state + * stack. + */ + p->yyss = (short *)Malloc(sizeof(short) * YYMAXDEPTH); + p->yyssp = p->yyss - 1; + p->yyvsp = p->yyvs = (YYSTYPE *)Malloc(sizeof(YYSTYPE) * YYMAXDEPTH); + p->tos_tos = &p->tos_stack[0]; + *p->tos_tos = p->yyvsp; + p->flags = &p->flags_stack[0]; + *p->flags = 0; + p->data = &p->data_stack[0]; + *p->data = 0; + p->pending_join = &p->pending_join_stack[0]; + p->pending_endif = &p->pending_endif_stack[0]; + *p->pending_join = *p->pending_endif = 0; + #ifdef YYLSP_NEEDED + p->yylsp = p->yyls = (YYLTYPE *)Malloc(sizeof(YYLTYPE) * YYMAXDEPTH); + #endif + p->yymaxdepth = YYMAXDEPTH; + /* make it a circular linked list */ + p->flink = p->blink = p; + #ifdef YYDEBUG + p->branch = &p->branch_stack[0]; + *p->branch = "TRUE branch"; + #endif + return p; + } + + kill_parse(p) + register parse p; + { + Free(p->yyss); + Free(p->yyvs); + #ifdef YYLSP_NEEDED + Free(p->yyls); + #endif + Free(p); + } + + unify_parses(p1, p2) + parse p1, p2; + { + register short *s1 = p1->yyssp; + register short *s2 = p2->yyssp; + + if (*p1->pending_join != p2 || *p2->pending_join != p1) + return 0; + + if (JUST_SHIFTED(p1) || JUST_SHIFTED(p2)) + return 0; + + if (!ACTIVE(p1) || !ACTIVE(p2)) + return 0; + + if ((!DONE_SOMETHING(p1) && !DONE_SOMETHING(p2)) || + (ACCEPTED(p1) && ACCEPTED(p2))) { + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Joining parse %x to parse %x\n", p1, p2); + #endif + return 1; + } + + if ((p1->yyvsp > *p1->tos_tos+1) || (p2->yyvsp > *p2->tos_tos+1)) + return 0; + + while (s1 != p1->yyss && s2 != p2->yyss) { + if (*s1 != *s2) + break; + s1--; s2--; + } + + if (s1 == p1->yyss && s2 == p2->yyss) { + #ifdef YYDEBUG + if (yydebug) { + fprintf(errfile, "Joining parse %x to parse %x\n", p1, p2); + } + #endif + return 1; + } + return 0; + } + + void realloc_stack(as, p) + ScanPtr as; + register parse p; + { + /* Give user a chance to reallocate the stack. */ + + + /* Get the current used size of the three stacks, in elements. */ + int size = p->yyssp - p->yyss + 1; + + if (p->yymaxdepth >= YYMAXLIMIT) + yyerror(as, "parser stack overflow"); + + p->yymaxdepth *= 2; + if (p->yymaxdepth > YYMAXLIMIT) + p->yymaxdepth = YYMAXLIMIT; + + p->yyss = (short *) Realloc(p->yyss, + p->yymaxdepth * (sizeof (*p->yyssp))); + p->yyvs = (YYSTYPE *) Realloc(p->yyvs, + p->yymaxdepth * (sizeof (*p->yyvsp))); + #ifdef YYLSP_NEEDED + p->yyls = (YYLTYPE *) Realloc(p->yyls, + p->yymaxdepth * (sizeof (*p->yylsp))); + #endif + + p->yyssp = p->yyss + size - 1; + p->yyvsp = p->yyvs + size - 1; + #ifdef YYLSP_NEEDED + p->yylsp = p->yyls + size - 1; + #endif + + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Stack size increased to %d\n", p->yymaxdepth); + #endif + + #if 0 + if (p->yyssp >= p->yyss + p->yymaxdepth - 1) + return + #endif + } + + #define REDUCTION 1 + + #if 0 + static parse + next_applicable_parse(p, parselist) + register parse p, parselist; + { + register parse l = parselist->flink; + + while (l != p) { + if (l->cur_token_number == p->cur_token_number) + break; + l = l->flink; + } + return l == p ? NULL : l; + } + #endif + + static void + notify_of_endif(p, limit, activelist, cur_token_number) + parse p; + parse limit; + parse *activelist; + { + parse *pending; + + --p->pending_endif; + p->cur_token_number = cur_token_number; + p->yychar = YYEMPTY; + SET_SEEN_ENDIF(p); + SET_SEEN_PP_TOKEN(p); + /* if p isn't active, make it so and put it on the activelist */ + if (!ACTIVE(p)) { + SET_ACTIVE(p); + if (*activelist == NULL) { + *activelist = p; + (*activelist)->flink = (*activelist)->blink = *activelist; + } else { + (*activelist)->blink->flink = p; + p->flink = *activelist; + p->blink = (*activelist)->blink; + (*activelist)->blink = p; + } + } + + for (pending = p->pending_join; *pending != limit; pending--) { + notify_of_endif(*pending, p, activelist, cur_token_number); + } + + } + + static parse + find_next_parse(parselist, cur_token_number) + register parse parselist; + { + register parse l, best_parse; + int parse_val, best_parse_val; + + if (parselist->flink == parselist) + if (ACCEPTED(parselist) || ABORTED(parselist)) + return NULL; + else + return parselist; + + l = parselist; + best_parse_val = -2; + best_parse = NULL; + do { + if (ACCEPTED(l) || ABORTED(l)) { + l = l->flink; + continue; + } + else if (l->cur_token_number < cur_token_number) + parse_val = 100000; + else + parse_val = 0; + + parse_val += l->yyssp - l->yyss; + if (parse_val > best_parse_val) { + best_parse_val = parse_val; + best_parse = l; + } else if (parse_val == best_parse_val && + *l->yyssp > *best_parse->yyssp) { + best_parse_val = parse_val; + best_parse = l; + } + + l = l->flink; + } while (l != parselist); + return best_parse; + } + + #define FALSE 0 + #define TRUE 1 + + all_blocked(parselist, cur_token_number) + parse parselist; + { + register parse l = parselist; + do { + if (l->cur_token_number != cur_token_number) + return FALSE; + l = l->flink; + } while (l != parselist); + return TRUE; + } + + static parse merge_parses(yyp, ap, activelist, currentfile) + parse yyp, ap; + parse *activelist; + FilePtr currentfile; + { + parse tmp; + + if (!IFDEF_FORK(yyp)) { + /* swap ap and yyp so that the result of the join + (yyp) is the true branch of the fork */ + tmp = ap; + ap = yyp; + yyp = tmp; + } + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Joining parse 0x%x and 0x%x.\n", + yyp, ap); + #endif + if (yyjoin) { + if (!yyp->last_reduction) + yyp->last_reduction = yyp->yyvsp; + if (!ap->last_reduction) + ap->last_reduction = ap->yyvsp; + *yyp->yyvsp = (*yyjoin)(yyp->last_reduction, + ap->last_reduction, + yyp->data, ap->data, + ¤tfile->cpp_skipping); + } + --yyp->pending_join; + --yyp->data; + --yyp->flags; + --yyp->tos_tos; + #ifdef YYDEBUG + --yyp->branch; + #endif + + /* get rid of the duplicate parse */ + ap->blink->flink = ap->flink; + ap->flink->blink = ap->blink; + if (ap == *activelist) + *activelist = ap->flink; + kill_parse(ap); + return yyp; + } + + static void merge_active(activelist, currentfile) + parse *activelist; + FilePtr currentfile; + { + parse yyp, ap; + int parses_merged; + + /* + * See if there are any parses that we can join. + */ + parses_merged = 1; + while (parses_merged && (*activelist)->flink != *activelist) { + parses_merged = 0; + yyp = *activelist; + do { + ap = *yyp->pending_join; + if (unify_parses(yyp, ap)) { + yyp = merge_parses(yyp, ap, activelist, currentfile); + parses_merged = 1; + } + yyp = yyp->flink; + } while (yyp != *activelist); + } + } + + #line 607 "bison.simple" + int yyparse(currentfile) + FilePtr currentfile; + { + int yychar1; /* lookahead token as an internal (translated) token number */ + + #ifndef YYPURE + int yyn; + #endif + + #ifdef YYDEBUG + extern int yydebug; + #endif + + YYSTYPE yyval; /* the variable used to return */ + /* semantic values from the action */ + /* routines */ + int yylen; + register parse yyp; + parse ap, activelist; + int curtoken, retval; + char *curtext, **oldtext; + YYSTYPE curlval, *oldlval; + YYLTYPE curlloc, *oldlloc; + int cur_token_number = 0; + + + oldtext = _yytext; + oldlval = _yylval; + oldlloc = _yylloc; + + activelist = start_parse(); + SET_ACTIVE(activelist); + + /* Go through parses in round-robin fashion. Activelist is a circular */ + /* doubly linked list. */ + while (yyp = find_next_parse(activelist, cur_token_number)) { + _yytext = &(yyp->text); + _yylval = &(yyp->lval); + _yylloc = &(yyp->lloc); + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Resuming parser %x %s\n", yyp, *yyp->branch); + #endif + if (yyswitch) + (*yyswitch)(yyp->data, ¤tfile->cpp_skipping); + + /* + * Figure out where to resume. If this parse has never + * seen a token, we start below the test statements, otherwise + * we start where we left off. + */ + #if 1 + if (yyp->blocked == REDUCTION) { + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "yyp->blocked == REDUCTION, yyp->token = %d, %d\n", yyp->cur_token_number, cur_token_number); + #endif + goto yyresume; + } + else + #endif + if (SEEN_PP_TOKEN(yyp)) { + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "SEEN_PP_TOKEN"); + #endif + goto yyresume; + } + else if (yyp->cur_token_number < 0) { + /* + * This is the start-up case for the parser. We have + * to set the token counter so that we will read the first + * token and then fall through to push the initial state. + */ + yyp->cur_token_number = cur_token_number; + } else + goto yyresume; + + /* + * Push a new state, which is found in yystate . In all + * cases, when you get here, the value and location stacks + * have just been pushed. so pushing a state here evens the + * stacks. + */ + yynewstate: + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "yynewstate: "); + #endif + *++yyp->yyssp = yyp->yystate; + SET_DONE_SOMETHING(yyp); + + if (yyp->yyssp >= yyp->yyss + yyp->yymaxdepth - 1) + realloc_stack(currentfile->as, yyp); + #ifdef YYDEBUG + if (yydebug) { + short *ssp1 = yyp->yyss - 1; + fprintf(errfile, "Entering state %d ", yyp->yystate); + fprintf (errfile, "state stack now"); + while (ssp1 != yyp->yyssp) + fprintf (errfile, " %d", *++ssp1); + fprintf (errfile, "\n"); + } + #endif + + /* + * We've already done the reduction. Now see if we can join this + * parse with its partner. + */ + if (SEEN_ENDIF(yyp) && (ap = *yyp->pending_join)) { + /* we should really make sure that both parses can be + reduced here */ + if (unify_parses(yyp, ap)) + yyp = merge_parses(yyp, ap, &activelist, currentfile); + } + + #if 2 + /* + * If we are here and blocked == REDUCTION, then we just + * did a reduction so we should block to see if there is a better + * candidate parse for reduction. + */ + if (yyp->blocked == REDUCTION) + continue; + #endif + + /* Do appropriate processing given the current state. Read + * a lookahead token if we need one and don't already have + * one. + */ + yyresume: + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "yyresume: "); + #endif + + /* First try to decide what to do without reference to + * lookahead token. + */ + + yyn = yypact[yyp->yystate]; + if (yyn == YYFLAG) + goto yydefault; + + /* Not known => get a lookahead token if don't already have + * one. + */ + + /* yychar is either YYEMPTY or YYEOF or a valid token in + * external form. + */ + + if (yyp->yychar == YYEMPTY) { + register parse newp; + int need_new_token; + + /* + * Synchronize on input. Suspend this parse if other + * parses haven't read the current token. + */ + if (!(need_new_token = all_blocked(activelist, cur_token_number)) && + yyp->cur_token_number == cur_token_number) + continue; + + if (need_new_token) { + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Reading a token: "); + #endif + yyp->yychar = curtoken = YYLEX; + curtext = yytext; + curlval = yylval; + curlloc = yylloc; + yyp->cur_token_number = ++cur_token_number; + } else { + yyp->yychar = curtoken; + yyp->text = curtext; + yyp->lval = curlval; + yyp->lloc = curlloc; + yyp->cur_token_number = cur_token_number; + } + + switch (yyp->yychar) { + parse tail; + int token_val; + + case PPELSE: + case PPELIF: + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Next token is ELSE\n"); + #endif + token_val = yyp->yychar; + + /* + * Swap role of active and sleeping parses + * by putting all currently active parses to sleep + * and waking all their partners. + */ + ap = activelist; /* save old activelist */ + activelist = NULL; /* nothing currently active */ + tail = ap; + + /* + * Now put the relevant sleeping parses back on + * activelist. + */ + { + parse nextap = 0, partner; + + for (; ap && nextap != tail; ap = nextap) { + nextap = ap->flink; + partner = *ap->pending_endif; + UNSET_ACTIVE(ap); + if (!ACTIVE(partner)) { + if (activelist == NULL) { + activelist = partner; + activelist->flink = activelist->blink = + activelist; + } else { + /* Put parse on end. Is this necessary? */ + activelist->blink->flink = partner; + partner->flink = activelist; + partner->blink = activelist->blink; + activelist->blink = partner; + } + /* force this parse to read new token */ + partner->cur_token_number = cur_token_number; + /* mark this parse as having just seen a + preprocessor token */ + UNSET_ALL(partner); + SET_SEEN_PP_TOKEN(partner); + SET_ACTIVE(partner); + } + } /* for loop */ + } /* compound stmt */ + + if (yyelse) + if (IFDEF_FORK(yyp)) + (*yyelse)(yyp->data, (*yyp->pending_endif)->data); + else + (*yyelse)((*yyp->pending_endif)->data, yyp->data); + + + yyp->yychar = YYEMPTY; + yyp = activelist->blink; + if (token_val == PPELSE) { + continue; + } else { + /* fall through to do IF part of PPELIF case */ ; + yyp->yychar = PPELIF; + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Next token was really ELSIF\n"); + #endif + } + case PPIFDEF: + case PPIF: + case PPIFNDEF: + + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Next token is IFDEF, IFNDEF, or IF. "); + #endif + /* save current tos for yyvs */ + *(++yyp->tos_tos) = yyp->yyvsp; + ++yyp->flags; + SET_JOIN_PENDING(yyp); + UNSET_SEEN_ENDIF(yyp); + SET_SEEN_PP_TOKEN(yyp); + SET_IFDEF_FORK(yyp); + SET_ACTIVE(yyp); + UNSET_DONE_SOMETHING(yyp); + ++yyp->pending_join; + ++yyp->pending_endif; + ++yyp->data; + + /* + * fork an alternate parse for this active parse. + */ + newp = start_parse(); + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, + "Splitting parse 0x%x. New parse is 0x%x.\n", + yyp, newp); + #endif + + #ifdef YYDEBUG + ++yyp->branch; + *yyp->branch = "TRUE branch"; + bcopy(yyp->branch_stack, newp->branch_stack, sizeof + newp->branch_stack); + newp->branch = newp->branch_stack + (yyp->branch - + yyp->branch_stack); + *newp->branch = "FALSE branch"; + #endif + bcopy(yyp->yyss, newp->yyss, + (yyp->yyssp - yyp->yyss + 1) * (sizeof *yyp->yyss)); + newp->yyssp = newp->yyss + (yyp->yyssp - yyp->yyss); + bcopy(yyp->yyvs, newp->yyvs, + (yyp->yyvsp - yyp->yyvs + 1) * (sizeof *yyp->yyvs)); + newp->yyvsp = newp->yyvs + (yyp->yyvsp - yyp->yyvs); + #ifdef YYLSP_NEEDED + bcopy(yyp->yyls, newp->yyls, + (yyp->yylsp - yyp->yyls + 1) * (sizeof *yyp->yyls)); + newp->yylsp = newp->yyls + (yyp->yylsp - yyp->yyls); + #endif + + { + int i; + for (i = 0; &yyp->tos_stack[i] <= yyp->tos_tos; i++) + newp->tos_stack[i] = newp->yyvs + + (yyp->tos_stack[i] - yyp->yyvs); + } + newp->tos_tos = newp->tos_stack + + (yyp->tos_tos - yyp->tos_stack); + + newp->lineno = yyp->lineno = yylineno(currentfile->as); + newp->yystate = yyp->yystate; + newp->yyerrstatus = yyp->yyerrstatus; + newp->yynerr = yyp->yynerr; + newp->yymaxdepth = yyp->yymaxdepth; + + bcopy(yyp->flags_stack, newp->flags_stack, + sizeof newp->flags_stack); + newp->flags = + newp->flags_stack + (yyp->flags - yyp->flags_stack); + UNSET_ALL(newp); + SET_JOIN_PENDING(newp); + + bcopy(yyp->pending_join_stack, newp->pending_join_stack, + sizeof newp->pending_join_stack); + newp->pending_join = + newp->pending_join_stack + (yyp->pending_join - + yyp->pending_join_stack); + *newp->pending_join = yyp; + *yyp->pending_join = newp; + + bcopy(yyp->pending_endif_stack, newp->pending_endif_stack, + sizeof newp->pending_endif_stack); + newp->pending_endif = + newp->pending_endif_stack + (yyp->pending_endif - + yyp->pending_endif_stack); + *newp->pending_endif = yyp; + *yyp->pending_endif = newp; + + bcopy(yyp->data_stack, newp->data_stack, sizeof + newp->data_stack); + newp->data = newp->data_stack + (yyp->data - yyp->data_stack); + + if (yyfork) + if (yyp->last_reduction) + *yyp->last_reduction = + (*yyfork)(yyp->last_reduction, + yyp->yychar, yytext, yyppval, + yyp->data, newp->data, + currentfile->cpp_skipping); + else + (void)(*yyfork)(yyp->last_reduction, + yyp->yychar, yytext, yyppval, + yyp->data, newp->data, + currentfile->cpp_skipping); + + yyp->cur_token_number = cur_token_number; + yyp->yychar = YYEMPTY; + + continue; /* do the next parse */ + + case PPENDIF: + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Next token is ENDIF\n"); + #endif + ap = *yyp->pending_endif; + + if (yyendif) + if (IFDEF_FORK(yyp)) + (*yyendif)(yyp->data, ap->data); + else + (*yyendif)(ap->data, yyp->data); + + notify_of_endif(yyp, ap, &activelist, cur_token_number); + notify_of_endif(ap, *ap->pending_endif, + &activelist, cur_token_number); + + /* all partners are now active and have been notified of + the #endif. See if there's anything we can join. */ + merge_active(&activelist, currentfile); + + continue; + + case PPDEFINE: + case PPINCLUDE: + case PPLINE: + yyp->yychar = YYEMPTY; + break; + } + } + /* This is a real token. Mark this parse has having seen one. */ + #ifdef YYDEBUG + if (yydebug && SEEN_PP_TOKEN(yyp)) + fprintf(errfile, "Unsetting SEEN_PP_TOKEN for %x, (%s).\n", yyp, + *yyp->branch); + #endif + UNSET_SEEN_PP_TOKEN(yyp); + + /* Convert token to internal form (in yychar1) for indexing + * tables with + */ + + if (yyp->yychar <= 0) { /* This means end of input. */ + yychar1 = 0; + yyp->yychar = YYEOF; /* Don't call YYLEX any more */ + + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Now at end of input.\n"); + #endif + } else { + yychar1 = YYTRANSLATE(yyp->yychar); + + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Next token is %d (%s, %s)\n", yyp->yychar, yytname[yychar1], yytext); + #endif + } + + yyn += yychar1; + if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != yychar1) + goto yydefault; + + yyn = yytable[yyn]; + + /* yyn is what to do for this token type in this state. + * Negative => reduce, -yyn is rule number. Positive => + * shift, yyn is new state. New state is final state => + * don't bother to shift, just return success. 0, or + * most negative number => error. + */ + + if (yyn < 0) { + if (yyn == YYFLAG) + goto yyerrlab; + yyn = -yyn; + goto yyreduce; + } else if (yyn == 0) + goto yyerrlab; + + if (yyn == YYFINAL) { + _yytext = oldtext; + _yylval = oldlval; + _yylloc = oldlloc; + YYACCEPT; + } + + /* Shift the lookahead token. */ + + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Shifting token %d (%s, %s), ", yyp->yychar, yytname[yychar1], yytext); + #endif + + /* Discard the token being shifted unless it is eof. */ + if (yyp->yychar != YYEOF) { + yyp->yychar = YYEMPTY; + *++yyp->yyvsp = yylval; + #ifdef YYLSP_NEEDED + ++yyp->yylsp; + *yyp->yylsp = yylloc; + #endif + SET_JUST_SHIFTED(yyp); + } + + /* count tokens shifted since error; after three, turn off + * error status. + */ + if (yyp->yyerrstatus) yyp->yyerrstatus--; + + yyp->yystate = yyn; + goto yynewstate; + + /* Do the default action for the current state. */ + yydefault: + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "yydefault: "); + #endif + yyn = yydefact[yyp->yystate]; + if (yyn == 0) + goto yyerrlab; + + /* Do a reduction. yyn is the number of a rule to reduce + * with. + */ + yyreduce: + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "yyreduce: "); + #endif + yylen = yyr2[yyn]; + yyval = (yyp->yyvsp)[1-yylen]; + /* implement default value of the action */ + + #ifdef YYDEBUG + if (yydebug) { + if (yylen == 1) + fprintf (errfile, "Reducing 1 value via line %d, ", + yyrline[yyn]); + else + fprintf (errfile, "Reducing %d values via line %d, ", + yylen, yyrline[yyn]); + } + #endif + + + $ /* the action file gets copied in in place of this dollarsign */ + #line 1120 "bison.simple" + + yyp->yyvsp -= yylen; + if (JOIN_PENDING(yyp) && yyp->yyvsp < *yyp->tos_tos) + *yyp->tos_tos = yyp->yyvsp; + *++yyp->yyvsp = yyval; + if (yylen > 0) { + yyp->last_reduction = yyp->yyvsp; + UNSET_JUST_SHIFTED(yyp); + } + + yyp->yyssp -= yylen; + #ifdef YYLSP_NEEDED + yyp->yylsp -= yylen; + #endif + + #ifdef YYDEBUG + if (yydebug) { + short *ssp1 = yyp->yyss - 1; + fprintf (errfile, "state stack now"); + while (ssp1 != yyp->yyssp) + fprintf (errfile, " %d", *++ssp1); + fprintf (errfile, "\n"); + + } + #endif + + #ifdef YYLSP_NEEDED + yyp->yylsp++; + if (yylen == 0) { + yyp->yylsp->first_line = yylloc.first_line; + yyp->yylsp->first_column = yylloc.first_column; + yyp->yylsp->last_line = (yyp->yylsp-1)->last_line; + yyp->yylsp->last_column = (yyp->yylsp-1)->last_column; + } else { + yyp->yylsp->last_line = (yyp->yylsp+yylen-1)->last_line; + yyp->yylsp->last_column = (yyp->yylsp+yylen-1)->last_column; + } + #endif + + + /* Now "shift" the result of the reduction. Determine + * what state that goes to, based on the state we popped + * back to and the rule number reduced by. + */ + + yyn = yyr1[yyn]; + + yyp->yystate = yypgoto[yyn - YYNTBASE] + *yyp->yyssp; + if (yyp->yystate >= 0 && yyp->yystate <= YYLAST && yycheck[yyp->yystate] == *yyp->yyssp) + yyp->yystate = yytable[yyp->yystate]; + else + yyp->yystate = yydefgoto[yyn - YYNTBASE]; + + yyp->blocked = REDUCTION; + goto yynewstate; + + yyerrlab: /* here on detecting error */ + + if (! yyp->yyerrstatus) { + if (yyp->flink == yyp || !(*yyskip)(yyp->data)) { + /* If not already recovering from an error, report this + error. */ + ++yyp->yynerr; + yyerror(currentfile->as, "parse error"); + if ((yyn = yypact[yyp->yystate]) > YYFLAG && yyn < YYLAST) + { + int x, count; + count = 0; + for (x = 3; x < (sizeof(yytname) / sizeof(char *)); x++) + { + if (yycheck[x + yyn] == x) + { + fprintf (errfile, "%s %s", + count == 0 ? "expecting:" : " or", + yytname[x]); + count++; + } + } + fprintf (errfile, "%s", count > 0 ? "\n" : ""); + } + } + else { + YYABORT; + } + } + + if (yyp->yyerrstatus == 3) { + + /* if just tried and failed to reuse lookahead token after + * an error, discard it. + */ + + /* return failure if at end of input */ + if (yyp->yychar == YYEOF) { + _yytext = oldtext; + _yylval = oldlval; + _yylloc = oldlloc; + YYABORT; + } + + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Discarding token %d (%s).\n", yyp->yychar, yytname[yychar1]); + #endif + + yyp->yychar = YYEMPTY; + } + + /* Else will try to reuse lookahead token + after shifting the error token. */ + + yyp->yyerrstatus = 3; /* Each real token shifted decrements this */ + + goto yyerrhandle; + + yyerrdefault: + + /* current state does not do anything special for the error + * token. + */ + + #if 0 + /* This is wrong; only states that explicitly want error + * tokens should shift them. + */ + yyn = yydefact[yyp->yystate]; + + /* If its default is to accept any token, ok. Otherwise pop + * it. + */ + if (yyn) goto yydefault; + #endif + + yyerrpop: + + /* pop the current state because it cannot handle the error token */ + + if (yyp->yyssp == yyp->yyss) { + _yytext = oldtext; + _yylval = oldlval; + _yylloc = oldlloc; + YYABORT; + } + yyp->yyvsp--; + yyp->yystate = *--yyp->yyssp; + #ifdef YYLSP_NEEDED + yyp->yylsp--; + #endif + + #ifdef YYDEBUG + if (yydebug) { + short *ssp1 = yyp->yyss - 1; + fprintf (errfile, "Error: state stack now"); + while (ssp1 != yyp->yyssp) + fprintf (errfile, " %d", *++ssp1); + fprintf (errfile, "\n"); + } + #endif + + yyerrhandle: + + yyn = yypact[yyp->yystate]; + if (yyn == YYFLAG) + goto yyerrdefault; + + yyn += YYTERROR; + if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != YYTERROR) + goto yyerrdefault; + + yyn = yytable[yyn]; + if (yyn < 0) { + if (yyn == YYFLAG) + goto yyerrpop; + yyn = -yyn; + goto yyreduce; + } else if (yyn == 0) + goto yyerrpop; + + if (yyn == YYFINAL) { + _yytext = oldtext; + _yylval = oldlval; + _yylloc = oldlloc; + YYACCEPT; + } + + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "Shifting error token, "); + #endif + + *++yyp->yyvsp = yylval; + #ifdef YYLSP_NEEDED + *++yyp->yylsp = yylloc; + #endif + + yyp->yystate = yyn; + goto yynewstate; + yyabort: + SET_ABORTED(yyp); + #ifdef YYDEBUG + if (yydebug) + fprintf(errfile, "yyabort for parse %x\n", yyp); + #endif + continue; + yyaccept: { + unsigned short *flags; + + UNSET_JUST_SHIFTED(yyp); /* Don't care that we just shifted the EOF + token. */ + for (flags = yyp->flags; flags >= yyp->flags_stack; flags--) + *flags |= ACCEPTED_BIT; + + #ifdef YYDEBUG + if (yydebug) { + short *ssp1 = yyp->yyss - 1; + fprintf(errfile, "yyaccept for parse %x\n", yyp); + fprintf (errfile, " state stack now"); + while (ssp1 != yyp->yyssp) + fprintf (errfile, " %d", *++ssp1); + fprintf (errfile, "\n"); + + } + #endif + continue; + } + + } /* end for loop */ + + merge_active(&activelist, currentfile); + + _yytext = oldtext; + _yylval = oldlval; + _yylloc = oldlloc; + + if (yyfinish) + yyfinish(activelist->yyvsp, ¤tfile->tree_root); + yyp = activelist; + retval = ABORTED(activelist) || activelist != activelist->flink; + do { + ap = yyp->flink; + kill_parse(yyp); + yyp = ap; + } while (yyp != activelist); + + return retval; + + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/closure.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/closure.c:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/closure.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,360 ---- + /* Subroutines for bison + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* subroutines of file LR0.c. + + Entry points: + + closure (items, n) + + Given a vector of item numbers items, of length n, + set up ruleset and itemset to indicate what rules could be run + and which items could be accepted when those items are the active ones. + + ruleset contains a bit for each rule. closure sets the bits + for all rules which could potentially describe the next input to be read. + + itemset is a vector of item numbers; itemsetend points to just beyond the end + of the part of it that is significant. + closure places there the indices of all items which represent units of + input that could arrive next. + + initialize_closure (n) + + Allocates the itemset and ruleset vectors, + and precomputes useful data so that closure can be called. + n is the number of elements to allocate for itemset. + + finalize_closure () + + Frees itemset, ruleset and internal data. + + */ + + #include + #include "machine.h" + #include "new.h" + #include "gram.h" + + extern short **derives; + + short *itemset; + short *itemsetend; + static unsigned *ruleset; + + /* internal data. See comments before set_fderives and set_firsts. */ + static unsigned *fderives; + static unsigned *firsts; + + /* number of words required to hold a bit for each rule */ + static int rulesetsize; + + /* number of words required to hold a bit for each variable */ + static int varsetsize; + + extern void RTC(unsigned *R,int n); + + void set_fderives(void); + void set_firsts(void); + + void initialize_closure(int n) + { + itemset = NEW2(n, short); + + rulesetsize = WORDSIZE(nrules + 1); + ruleset = NEW2(rulesetsize, unsigned); + + set_fderives(); + } + + /* set fderives to an nvars by nrules matrix of bits + indicating which rules can help derive the beginning of the data + for each nonterminal. For example, if symbol 5 can be derived as + the sequence of symbols 8 3 20, and one of the rules for deriving + symbol 8 is rule 4, then the [5 - ntokens, 4] bit in fderives is set. */ + + void set_fderives(void) + { + register unsigned *rrow; + register unsigned *vrow; + register int j; + register unsigned mask; + register unsigned cword; + register short *rp; + + int ruleno; + int i; + + fderives = NEW2(nvars * rulesetsize, unsigned) - ntokens * rulesetsize; + + set_firsts(); + + rrow = fderives + ntokens * rulesetsize; + + for (i = ntokens; i < nsyms; i++) + { + vrow = firsts + ((i - ntokens) * varsetsize); + cword = *vrow++; + mask = 1; + for (j = ntokens; j < nsyms; j++) + { + if (cword & mask) + { + rp = derives[j]; + while ((ruleno = *rp++) > 0) + { + SETBIT(rrow, ruleno); + } + } + + mask <<= 1; + if (mask == 0 && j + 1 < nsyms) + { + cword = *vrow++; + mask = 1; + } + } + + vrow += varsetsize; + rrow += rulesetsize; + } + + #ifdef DEBUG + print_fderives(); + #endif + + FREE(firsts); + } + + /* set firsts to be an nvars by nvars bit matrix indicating which items + can represent the beginning of the input corresponding to which other items. + For example, if some rule expands symbol 5 into the sequence of symbols 8 3 20, + the symbol 8 can be the beginning of the data for symbol 5, + so the bit [8 - ntokens, 5 - ntokens] in firsts is set. */ + + void set_firsts(void) + { + register unsigned *row; + /* register int done; JF unused */ + register int symbol; + register short *sp; + register int rowsize; + + int i; + + varsetsize = rowsize = WORDSIZE(nvars); + + firsts = NEW2(nvars * rowsize, unsigned); + + row = firsts; + for (i = ntokens; i < nsyms; i++) + { + sp = derives[i]; + while (*sp >= 0) + { + symbol = ritem[rrhs[*sp++]]; + if (ISVAR(symbol)) + { + symbol -= ntokens; + SETBIT(row, symbol); + } + } + + row += rowsize; + } + + RTC(firsts, nvars); + + #ifdef DEBUG + print_firsts(); + #endif + } + + void closure(short *core,int n) + { + register int ruleno; + register unsigned word; + register unsigned mask; + register short *csp; + register unsigned *dsp; + register unsigned *rsp; + + short *csend; + unsigned *rsend; + int symbol; + int itemno; + + rsp = ruleset; + rsend = ruleset + rulesetsize; + csend = core + n; + + if (n == 0) + { + dsp = fderives + start_symbol * rulesetsize; + while (rsp < rsend) + *rsp++ = *dsp++; + } + else + { + while (rsp < rsend) + *rsp++ = 0; + + csp = core; + while (csp < csend) + { + symbol = ritem[*csp++]; + if (ISVAR(symbol)) + { + dsp = fderives + symbol * rulesetsize; + rsp = ruleset; + while (rsp < rsend) + *rsp++ |= *dsp++; + } + } + } + + ruleno = 0; + itemsetend = itemset; + csp = core; + rsp = ruleset; + while (rsp < rsend) + { + word = *rsp++; + if (word == 0) + { + ruleno += BITS_PER_WORD; + } + else + { + mask = 1; + while (mask) + { + if (word & mask) + { + itemno = rrhs[ruleno]; + while (csp < csend && *csp < itemno) + *itemsetend++ = *csp++; + *itemsetend++ = itemno; + } + + mask <<= 1; + ruleno++; + } + } + } + + while (csp < csend) + *itemsetend++ = *csp++; + + #ifdef DEBUG + print_closure(n); + #endif + } + + void finalize_closure(void) + { + FREE(itemset); + FREE(ruleset); + FREE(fderives + ntokens * rulesetsize); + } + + #ifdef DEBUG + + void print_closure(int n) + { + register short *isp; + + printf("\n\nn = %d\n\n", n); + for (isp = itemset; isp < itemsetend; isp++) + printf(" %d\n", *isp); + } + + void print_firsts(void) + { + register int i; + register int j; + register unsigned *rowp; + register unsigned cword; + register unsigned mask; + + extern char **tags; + + printf("\n\n\nFIRSTS\n\n"); + + for (i = ntokens; i < nsyms; i++) + { + printf("\n\n%s firsts\n\n", tags[i]); + + rowp = firsts + ((i - ntokens) * vrowsize); + + cword = *rowp++; + mask = 1; + for (j = 0; j < nsyms; j++) + { + if (cword & mask) + printf(" %s\n", tags[j + ntokens]); + + mask <<= 1; + + if (mask == 0 && j + 1 < nsyms) + { + cword = *rowp++; + mask = 1; + } + } + } + } + + void print_fderives(void) + { + register int i; + register int j; + register unsigned *rp; + register unsigned cword; + register unsigned mask; + + extern char **tags; + + printf("\n\n\nFDERIVES\n"); + + for (i = ntokens; i < nsyms; i++) + { + printf("\n\n%s derives\n\n", tags[i]); + rp = fderives + i * rrowsize; + cword = *rp++; + mask = 1; + for (j = 0; j <= nrules; j++) + { + if (cword & mask) + printf(" %d\n", j); + + mask <<= 1; + if (mask == 0 && j + 1 < nrules) + { + cword = *rp++; + mask = 1; + } + } + } + + fflush(stdout); + } + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/conflicts.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/conflicts.c:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/conflicts.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,728 ---- + /* Find and resolve or report look-ahead conflicts for bison, + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + #include + #include + #include "machine.h" + #include "new.h" + #include "files.h" + #include "gram.h" + #include "state.h" + + + #ifdef USG + #include + #define bcopy(src, dst, num) memcpy((dst), (src), (num)) + #endif + + #ifdef sparc + #include + #endif + + #define alloca1(x) malloc(x) + + extern char **tags; + extern int tokensetsize; + extern char *consistent; + extern short *accessing_symbol; + extern shifts **shift_table; + extern unsigned *LA; + extern short *LAruleno; + extern short *lookaheads; + extern int verboseflag; + + /* + extern char *alloca (); + */ + + char any_conflicts; + char *conflicts; + errs **err_table; + int expected_conflicts; + + + static unsigned *shiftset; + static unsigned *lookaheadset; + static int src_total; + static int rrc_total; + static int src_count; + static int rrc_count; + + void set_conflicts(int state); + void resolve_sr_conflict(int state,int lookaheadnum); + void flush_shift(int state,int token); + void log_resolution(int state,int LAno,int token,char *resolution); + void total_conflicts(void); + void count_sr_conflicts(int state); + void count_rr_conflicts(int state); + + void initialize_conflicts(void) + { + register int i; + /* register errs *sp; JF unused */ + + conflicts = NEW2(nstates, char); + shiftset = NEW2(tokensetsize, unsigned); + lookaheadset = NEW2(tokensetsize, unsigned); + + err_table = NEW2(nstates, errs *); + + any_conflicts = 0; + + for (i = 0; i < nstates; i++) + set_conflicts(i); + } + + + + void set_conflicts(int state) + { + register int i; + register int k; + register shifts *shiftp; + register unsigned *fp2; + register unsigned *fp3; + register unsigned *fp4; + register unsigned *fp1; + register int symbol; + + if (consistent[state]) return; + + for (i = 0; i < tokensetsize; i++) + lookaheadset[i] = 0; + + shiftp = shift_table[state]; + if (shiftp) + { + k = shiftp->nshifts; + for (i = 0; i < k; i++) + { + symbol = accessing_symbol[shiftp->shifts[i]]; + if (ISVAR(symbol)) break; + SETBIT(lookaheadset, symbol); + } + } + + k = lookaheads[state + 1]; + fp4 = lookaheadset + tokensetsize; + + /* loop over all rules which require lookahead in this state */ + /* first check for shift-reduce conflict, and try to resolve using precedence */ + + for (i = lookaheads[state]; i < k; i++) + if (rprec[LAruleno[i]]) + { + fp1 = LA + i * tokensetsize; + fp2 = fp1; + fp3 = lookaheadset; + + while (fp3 < fp4) + { + if (*fp2++ & *fp3++) + { + resolve_sr_conflict(state, i); + break; + } + } + } + + /* loop over all rules which require lookahead in this state */ + /* Check for conflicts not resolved above. */ + + for (i = lookaheads[state]; i < k; i++) + { + fp1 = LA + i * tokensetsize; + fp2 = fp1; + fp3 = lookaheadset; + + while (fp3 < fp4) + { + if (*fp2++ & *fp3++) + { + conflicts[state] = 1; + any_conflicts = 1; + } + } + + fp2 = fp1; + fp3 = lookaheadset; + + while (fp3 < fp4) + *fp3++ |= *fp2++; + } + } + + /* Attempt to resolve shift-reduce conflict for one rule + by means of precedence declarations. + It has already been checked that the rule has a precedence. + A conflict is resolved by modifying the shift or reduce tables + so that there is no longer a conflict. */ + + void resolve_sr_conflict(int state,int lookaheadnum) + { + register int i; + register int mask; + register unsigned *fp1; + register unsigned *fp2; + register int redprec; + errs *errp = (errs *) alloca1 (sizeof(errs) + ntokens * sizeof(short)); + short *errtokens = errp->errs; + + /* find the rule to reduce by to get precedence of reduction */ + redprec = rprec[LAruleno[lookaheadnum]]; + + mask = 1; + fp1 = LA + lookaheadnum * tokensetsize; + fp2 = lookaheadset; + for (i = 0; i < ntokens; i++) + { + if ((mask & *fp2 & *fp1) && sprec[i]) + /* shift-reduce conflict occurs for token number i and it has a precision. + The precedence of shifting is that of token i. */ + { + if (sprec[i] < redprec) + { + if (verboseflag) log_resolution(state, lookaheadnum, i, "reduce"); + *fp2 &= ~mask; /* flush the shift for this token */ + flush_shift(state, i); + } + else if (sprec[i] > redprec) + { + if (verboseflag) log_resolution(state, lookaheadnum, i, "shift"); + *fp1 &= ~mask; /* flush the reduce for this token */ + } + else + { + /* Matching precedence levels. + For left association, keep only the reduction. + For right association, keep only the shift. + For nonassociation, keep neither. */ + + switch (sassoc[i]) + { + + case RIGHT_ASSOC: + if (verboseflag) log_resolution(state, lookaheadnum, i, "shift"); + break; + + case LEFT_ASSOC: + if (verboseflag) log_resolution(state, lookaheadnum, i, "reduce"); + break; + + case NON_ASSOC: + if (verboseflag) log_resolution(state, lookaheadnum, i, "an error"); + break; + } + + if (sassoc[i] != RIGHT_ASSOC) + { + *fp2 &= ~mask; /* flush the shift for this token */ + flush_shift(state, i); + } + if (sassoc[i] != LEFT_ASSOC) + { + *fp1 &= ~mask; /* flush the reduce for this token */ + } + if (sassoc[i] == NON_ASSOC) + { + /* Record an explicit error for this token. */ + *errtokens++ = i; + } + } + } + + mask <<= 1; + if (mask == 0) + { + mask = 1; + fp2++; fp1++; + } + } + errp->nerrs = errtokens - errp->errs; + if (errp->nerrs) + { + /* Some tokens have been explicitly made errors. Allocate + a permanent errs structure for this state, to record them. */ + i = (char *) errtokens - (char *) errp; + err_table[state] = (errs *) mallocate ((unsigned int)i); + bcopy (errp, err_table[state], i); + } + else + err_table[state] = 0; + } + + + + /* turn off the shift recorded for the specified token in the specified state. + Used when we resolve a shift-reduce conflict in favor of the reduction. */ + + void flush_shift(int state,int token) + { + register shifts *shiftp; + register int k, i; + /* register unsigned symbol; JF unused */ + + shiftp = shift_table[state]; + + if (shiftp) + { + k = shiftp->nshifts; + for (i = 0; i < k; i++) + { + if (shiftp->shifts[i] && token == accessing_symbol[shiftp->shifts[i]]) + (shiftp->shifts[i]) = 0; + } + } + } + + + + void log_resolution(int state,int LAno,int token,char *resolution) + { + fprintf(foutput, + "Conflict in state %d between rule %d and token %s resolved as %s.\n", + state, LAruleno[LAno], tags[token], resolution); + } + + + + void conflict_log(void) + { + register int i; + + src_total = 0; + rrc_total = 0; + + for (i = 0; i < nstates; i++) + { + if (conflicts[i]) + { + count_sr_conflicts(i); + count_rr_conflicts(i); + src_total += src_count; + rrc_total += rrc_count; + } + } + + total_conflicts(); + } + + + + void verbose_conflict_log(void) + { + register int i; + + src_total = 0; + rrc_total = 0; + + for (i = 0; i < nstates; i++) + { + if (conflicts[i]) + { + count_sr_conflicts(i); + count_rr_conflicts(i); + src_total += src_count; + rrc_total += rrc_count; + + fprintf(foutput, "State %d contains", i); + + if (src_count == 1) + fprintf(foutput, " 1 shift/reduce conflict"); + else if (src_count > 1) + fprintf(foutput, " %d shift/reduce conflicts", src_count); + + if (src_count > 0 && rrc_count > 0) + fprintf(foutput, " and"); + + if (rrc_count == 1) + fprintf(foutput, " 1 reduce/reduce conflict"); + else if (rrc_count > 1) + fprintf(foutput, " %d reduce/reduce conflicts", rrc_count); + + putc('.', foutput); + putc('\n', foutput); + } + } + + total_conflicts(); + } + + + + void total_conflicts(void) + { + if (src_total == expected_conflicts && rrc_total == 0) + return; + + fprintf(stderr, "%s contains", infile); + + if (src_total == 1) + fprintf(stderr, " 1 shift/reduce conflict"); + else if (src_total > 1) + fprintf(stderr, " %d shift/reduce conflicts", src_total); + + if (src_total > 0 && rrc_total > 0) + fprintf(stderr, " and"); + + if (rrc_total == 1) + fprintf(stderr, " 1 reduce/reduce conflict"); + else if (rrc_total > 1) + fprintf(stderr, " %d reduce/reduce conflicts", rrc_total); + + putc('.', stderr); + putc('\n', stderr); + } + + + + void count_sr_conflicts(int state) + { + register int i; + register int k; + register int mask; + register shifts *shiftp; + register unsigned *fp1; + register unsigned *fp2; + register unsigned *fp3; + register int symbol; + + src_count = 0; + + shiftp = shift_table[state]; + if (!shiftp) return; + + for (i = 0; i < tokensetsize; i++) + { + shiftset[i] = 0; + lookaheadset[i] = 0; + } + + k = shiftp->nshifts; + for (i = 0; i < k; i++) + { + if (! shiftp->shifts[i]) continue; + symbol = accessing_symbol[shiftp->shifts[i]]; + if (ISVAR(symbol)) break; + SETBIT(shiftset, symbol); + } + + k = lookaheads[state + 1]; + fp3 = lookaheadset + tokensetsize; + + for (i = lookaheads[state]; i < k; i++) + { + fp1 = LA + i * tokensetsize; + fp2 = lookaheadset; + + while (fp2 < fp3) + *fp2++ |= *fp1++; + } + + fp1 = shiftset; + fp2 = lookaheadset; + + while (fp2 < fp3) + *fp2++ &= *fp1++; + + mask = 1; + fp2 = lookaheadset; + for (i = 0; i < ntokens; i++) + { + if (mask & *fp2) + src_count++; + + mask <<= 1; + if (mask == 0) + { + mask = 1; + fp2++; + } + } + } + + void count_rr_conflicts(int state) + { + register int i; + register int j; + register int count; + register unsigned mask; + register unsigned *baseword; + register unsigned *wordp; + register int m; + register int n; + + rrc_count = 0; + + m = lookaheads[state]; + n = lookaheads[state + 1]; + + if (n - m < 2) return; + + mask = 1; + baseword = LA + m * tokensetsize; + for (i = 0; i < ntokens; i++) + { + wordp = baseword; + + count = 0; + for (j = m; j < n; j++) + { + if (mask & *wordp) + count++; + + wordp += tokensetsize; + } + + if (count >= 2) rrc_count++; + + mask <<= 1; + if (mask == 0) + { + mask = 1; + baseword++; + } + } + } + + + + void print_reductions(int state) + { + register int i; + register int j; + register int k; + register unsigned *fp1; + register unsigned *fp2; + register unsigned *fp3; + register unsigned *fp4; + register int rule; + register int symbol; + register unsigned mask; + register int m; + register int n; + register int default_LA; + register int default_rule; + register int cmax; + register int count; + register shifts *shiftp; + register errs *errp; + int nodefault = 0; + + for (i = 0; i < tokensetsize; i++) + shiftset[i] = 0; + + shiftp = shift_table[state]; + if (shiftp) + { + k = shiftp->nshifts; + for (i = 0; i < k; i++) + { + if (! shiftp->shifts[i]) continue; + symbol = accessing_symbol[shiftp->shifts[i]]; + if (ISVAR(symbol)) break; + /* if this state has a shift for the error token, + don't use a default rule. */ + if (symbol == error_token_number) nodefault = 1; + SETBIT(shiftset, symbol); + } + } + + errp = err_table[state]; + if (errp) + { + k = errp->nerrs; + for (i = 0; i < k; i++) + { + if (! errp->errs[i]) continue; + symbol = errp->errs[i]; + SETBIT(shiftset, symbol); + } + } + + m = lookaheads[state]; + n = lookaheads[state + 1]; + + if (n - m == 1 && ! nodefault) + { + default_rule = LAruleno[m]; + + fp1 = LA + m * tokensetsize; + fp2 = shiftset; + fp3 = lookaheadset; + fp4 = lookaheadset + tokensetsize; + + while (fp3 < fp4) + *fp3++ = *fp1++ & *fp2++; + + mask = 1; + fp3 = lookaheadset; + + for (i = 0; i < ntokens; i++) + { + if (mask & *fp3) + fprintf(foutput, " %-4s\t[reduce %d (%s)]\n", + tags[i], default_rule, tags[rlhs[default_rule]]); + + mask <<= 1; + if (mask == 0) + { + mask = 1; + fp3++; + } + } + + fprintf(foutput, " $default\treduce %d (%s)\n\n", + default_rule, tags[rlhs[default_rule]]); + } + else if (n - m >= 1) + { + cmax = 0; + default_LA = -1; + fp4 = lookaheadset + tokensetsize; + + if (! nodefault) + for (i = m; i < n; i++) + { + fp1 = LA + i * tokensetsize; + fp2 = shiftset; + fp3 = lookaheadset; + + while (fp3 < fp4) + *fp3++ = *fp1++ & ( ~ (*fp2++)); + + count = 0; + mask = 1; + fp3 = lookaheadset; + for (j = 0; j < ntokens; j++) + { + if (mask & *fp3) + count++; + + mask <<= 1; + if (mask == 0) + { + mask = 1; + fp3++; + } + } + + if (count > cmax) + { + cmax = count; + default_LA = i; + default_rule = LAruleno[i]; + } + + fp2 = shiftset; + fp3 = lookaheadset; + + while (fp3 < fp4) + *fp2++ |= *fp3++; + } + + for (i = 0; i < tokensetsize; i++) + shiftset[i] = 0; + + if (shiftp) + { + k = shiftp->nshifts; + for (i = 0; i < k; i++) + { + if (! shiftp->shifts[i]) continue; + symbol = accessing_symbol[shiftp->shifts[i]]; + if (ISVAR(symbol)) break; + SETBIT(shiftset, symbol); + } + } + + mask = 1; + fp1 = LA + m * tokensetsize; + fp2 = shiftset; + for (i = 0; i < ntokens; i++) + { + int defaulted = 0; + + if (mask & *fp2) + count = 1; + else + count = 0; + + fp3 = fp1; + for (j = m; j < n; j++) + { + if (mask & *fp3) + { + if (count == 0) + { + if (j != default_LA) + { + rule = LAruleno[j]; + fprintf(foutput, " %-4s\treduce %d (%s)\n", + tags[i], rule, tags[rlhs[rule]]); + } + else defaulted = 1; + + count++; + } + else + { + if (defaulted) + { + rule = LAruleno[default_LA]; + fprintf(foutput, " %-4s\treduce %d (%s)\n", + tags[i], rule, tags[rlhs[rule]]); + defaulted = 0; + } + rule = LAruleno[j]; + fprintf(foutput, " %-4s\t[reduce %d (%s)]\n", + tags[i], rule, tags[rlhs[rule]]); + } + } + + fp3 += tokensetsize; + } + + mask <<= 1; + if (mask == 0) + { + mask = 1; + fp1++; + } + } + + if (default_LA >= 0) + { + fprintf(foutput, " $default\treduce %d (%s)\n", + default_rule, tags[rlhs[default_rule]]); + } + + putc('\n', foutput); + } + } + + + + void finalize_conflicts(void) + { + FREE(conflicts); + FREE(shiftset); + FREE(lookaheadset); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/derives.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/derives.c:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/derives.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,111 ---- + /* Match rules with nonterminals for bison, + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* set_derives finds, for each variable (nonterminal), which rules can derive it. + It sets up the value of derives so that + derives[i - ntokens] points to a vector of rule numbers, terminated with a zero. */ + + #include + #include + #include "new.h" + #include "types.h" + #include "gram.h" + + short **derives; + + void set_derives(void) + { + register int i; + register int lhs; + register shorts *p; + register short *q; + register shorts **dset; + register shorts *delts; + + dset = NEW2(nvars, shorts *) - ntokens; + delts = NEW2(nrules + 1, shorts); + + p = delts; + for (i = nrules; i > 0; i--) + { + lhs = rlhs[i]; + p->next = dset[lhs]; + p->value = i; + dset[lhs] = p; + p++; + } + + derives = NEW2(nvars, short *) - ntokens; + q = NEW2(nvars + nrules, short); + + for (i = ntokens; i < nsyms; i++) + { + derives[i] = q; + p = dset[i]; + while (p) + { + *q++ = p->value; + p = p->next; + } + *q++ = -1; + } + + #ifdef DEBUG + print_derives(); + #endif + + FREE(dset + ntokens); + FREE(delts); + } + + + void free_derives(void) + { + FREE(derives[ntokens]); + FREE(derives + ntokens); + } + + + + #ifdef DEBUG + + void print_derives(void) + { + register int i; + register short *sp; + + extern char **tags; + + printf("\n\n\nDERIVES\n\n"); + + for (i = ntokens; i < nsyms; i++) + { + printf("%s derives", tags[i]); + for (sp = derives[i]; *sp > 0; sp++) + { + printf(" %d", *sp); + } + putchar('\n'); + } + + putchar('\n'); + } + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/files.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/files.c:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/files.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,287 ---- + /* Open and close files for bison, + Copyright (C) 1984, 1986 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + #ifdef VMS + #include + #define unlink delete + #define XPFILE "GNU_BISON:[000000]BISON.SIMPLE" + #define XPFILE1 "GNU_BISON:[000000]BISON.HAIRY" + #endif + /* + #define XPFILE "GNU_BISON:[000000]BISON.SIMPLE" + #define XPFILE1 "GNU_BISON:[000000]BISON.HAIRY" + */ + + #include + #include + #include "files.h" + #include "new.h" + #include "gram.h" + + FILE *finput = NULL; + FILE *foutput = NULL; + FILE *fdefines = NULL; + FILE *ftable = NULL; + FILE *fattrs = NULL; + FILE *fguard = NULL; + FILE *faction = NULL; + FILE *fparser = NULL; + + /* File name specified with -o for the output file, or 0 if no -o. */ + char *spec_outfile; + + char *infile; + char *outfile; + char *defsfile; + char *tabfile; + char *attrsfile; + char *guardfile; + char *actfile; + char *tmpattrsfile; + char *tmptabfile; + + char *mktemp(); /* So the compiler won't complain */ + FILE *tryopen(); /* This might be a good idea */ + + extern int verboseflag; + extern int definesflag; + int fixed_outfiles = 0; + + void done(int k); + + char *stringappend(char *string1,int end1,char *string2) + { + register char *ostring; + register char *cp, *cp1; + register int i; + + cp = string2; i = 0; + while (*cp++) i++; + + ostring = NEW2(i+end1+1, char); + + cp = ostring; + cp1 = string1; + for (i = 0; i < end1; i++) + *cp++ = *cp1++; + + cp1 = string2; + while (*cp++ = *cp1++) ; + + return ostring; + } + + + /* JF this has been hacked to death. Nowaday it sets up the file names for + the output files, and opens the tmp files and the parser */ + void openfiles(void) + { + char *name_base; + register char *cp; + char *filename; + int base_length; + int short_base_length; + + #ifdef VMS + char *tmp_base = "sys$scratch:b_"; + #else + char *tmp_base = "/tmp/b."; + #endif + int tmp_len = strlen (tmp_base); + + if (spec_outfile) + { + /* -o was specified. The precise -o name will be used for ftable. + For other output files, remove the ".c" or ".tab.c" suffix. */ + name_base = spec_outfile; + /* BASE_LENGTH includes ".tab" but not ".c". */ + base_length = strlen (name_base); + if (!strcmp (name_base + base_length - 2, ".c")) + base_length -= 2; + /* SHORT_BASE_LENGTH includes neither ".tab" nor ".c". */ + short_base_length = base_length; + if (!strcmp (name_base + short_base_length - 4, ".tab")) + short_base_length -= 4; + else if (!strcmp (name_base + short_base_length - 4, "_tab")) + short_base_length -= 4; + } + else + { + /* -o was not specified; compute output file name from input + or use y.tab.c, etc., if -y was specified. */ + + name_base = fixed_outfiles ? "y.y" : infile; + + /* Discard any directory names from the input file name + to make the base of the output. */ + cp = name_base; + while (*cp) + { + if (*cp == '/') + name_base = cp+1; + cp++; + } + + /* BASE_LENGTH gets length of NAME_BASE, sans ".y" suffix if any. */ + + base_length = strlen (name_base); + if (!strcmp (name_base + base_length - 2, ".y")) + base_length -= 2; + short_base_length = base_length; + + #ifdef VMS + name_base = stringappend(name_base, short_base_length, "_tab"); + #else + name_base = stringappend(name_base, short_base_length, ".tab"); + #endif + base_length = short_base_length + 4; + } + + finput = tryopen(infile, "r"); + + filename = (char *) getenv ("BISON_SIMPLE"); + fparser = tryopen(filename ? filename : PFILE, "r"); + + if (verboseflag) + { + outfile = stringappend(name_base, short_base_length, ".output"); + foutput = tryopen(outfile, "w"); + } + + if (definesflag) + { + defsfile = stringappend(name_base, base_length, ".h"); + fdefines = tryopen(defsfile, "w"); + } + + actfile = mktemp(stringappend(tmp_base, tmp_len, "act.XXXXXX")); + faction = tryopen(actfile, "w+"); + unlink(actfile); + + tmpattrsfile = mktemp(stringappend(tmp_base, tmp_len, "attrs.XXXXXX")); + fattrs = tryopen(tmpattrsfile,"w+"); + unlink(tmpattrsfile); + + tmptabfile = mktemp(stringappend(tmp_base, tmp_len, "tab.XXXXXX")); + ftable = tryopen(tmptabfile, "w+"); + unlink(tmptabfile); + + /* These are opened by `done' or `open_extra_files', if at all */ + if (spec_outfile) + tabfile = spec_outfile; + else + tabfile = stringappend(name_base, base_length, ".c"); + + #ifdef VMS + attrsfile = stringappend(name_base, short_base_length, "_stype.h"); + guardfile = stringappend(name_base, short_base_length, "_guard.c"); + #else + attrsfile = stringappend(name_base, short_base_length, ".stype.h"); + guardfile = stringappend(name_base, short_base_length, ".guard.c"); + #endif + } + + + + /* open the output files needed only for the semantic parser. + This is done when %semantic_parser is seen in the declarations section. */ + + void open_extra_files(void) + { + FILE *ftmp; + int c; + char *filename; + /* JF change open parser file */ + fclose(fparser); + filename = (char *) getenv ("BISON_HAIRY"); + fparser= tryopen(filename ? filename : PFILE1, "r"); + + /* JF change from inline attrs file to separate one */ + ftmp = tryopen(attrsfile, "w"); + rewind(fattrs); + while((c=getc(fattrs))!=EOF) /* Thank god for buffering */ + putc(c,ftmp); + fclose(fattrs); + fattrs=ftmp; + + fguard = tryopen(guardfile, "w"); + + } + + /* JF to make file opening easier. This func tries to open file + NAME with mode MODE, and prints an error message if it fails. */ + FILE *tryopen(char *name,char *mode) + { + FILE *ptr; + + ptr = fopen(name, mode); + if (ptr == NULL) + { + fprintf(stderr, "bison: "); + perror(name); + done(2); + } + return ptr; + } + + void done(int k) + { + if (faction) + fclose(faction); + + if (fattrs) + fclose(fattrs); + + if (fguard) + fclose(fguard); + + if (finput) + fclose(finput); + + if (fparser) + fclose(fparser); + + if (foutput) + fclose(foutput); + + /* JF write out the output file */ + if (k == 0 && ftable) + { + FILE *ftmp; + register int c; + + ftmp=tryopen(tabfile, "w"); + rewind(ftable); + while((c=getc(ftable)) != EOF) + putc(c,ftmp); + fclose(ftmp); + fclose(ftable); + } + + #ifdef VMS + delete(actfile); + delete(tmpattrsfile); + delete(tmptabfile); + if (k==0) sys$exit(SS$_NORMAL); + sys$exit(SS$_ABORT); + #else + exit(k); + #endif + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/files.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/files.h:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/files.h Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,47 ---- + /* File names and variables for bison, + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* These two should be pathnames for opening the sample parser files. + When bison is installed, they should be absolute pathnames. + XPFILE1 and XPFILE2 normally come from the Makefile. */ + + #define PFILE "parse.y.in" /* Simple parser */ + #define PFILE1 "parse.y.in" /* Semantic parser */ + + extern FILE *finput; /* read grammar specifications */ + extern FILE *foutput; /* optionally output messages describing the actions taken */ + extern FILE *fdefines; /* optionally output #define's for token numbers. */ + extern FILE *ftable; /* output the tables and the parser */ + extern FILE *fattrs; /* if semantic parser, output a .h file that defines YYSTYPE */ + /* and also contains all the %{ ... %} definitions. */ + extern FILE *fguard; /* if semantic parser, output yyguard, containing all the guard code */ + extern FILE *faction; /* output all the action code; precise form depends on which parser */ + extern FILE *fparser; /* read the parser to copy into ftable */ + + /* File name specified with -o for the output file, or 0 if no -o. */ + extern char *spec_outfile; + + extern char *infile; + extern char *outfile; + extern char *defsfile; + extern char *tabfile; + extern char *attrsfile; + extern char *guardfile; + extern char *actfile; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/getargs.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/getargs.c:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/getargs.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,94 ---- + /* Parse command line arguments for bison, + Copyright (C) 1984, 1986 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + #include + #include "files.h" + + int verboseflag; + int definesflag; + int debugflag; + int nolinesflag; + extern int fixed_outfiles;/* JF */ + + extern void fatal(char *s); + extern int getopt(int argc,char **argv,char *optstring); + + void getargs(int argc,char *argv[]) + { + register int c; + char *p = argv[0]; + char *lastcomponent; + + extern int optind; + extern char *optarg; + + verboseflag = 0; + definesflag = 0; + debugflag = 0; + fixed_outfiles = 0; + + /* See if the program was invoked as "yacc". */ + + lastcomponent = p; + while (*p) + { + if (*p == '/') + lastcomponent = p + 1; + p++; + } + if (! strcmp (lastcomponent, "yacc")) + /* If so, pretend we have "-y" as argument. */ + fixed_outfiles = 1; + + while ((c = getopt (argc, argv, "yvdlto:")) != EOF) + switch (c) + { + case 'y': + fixed_outfiles = 1; + break; + + case 'v': + verboseflag = 1; + break; + + case 'd': + definesflag = 1; + break; + + case 'l': + nolinesflag = 1; + break; + + case 't': + debugflag = 1; + break; + + case 'o': + spec_outfile = optarg; + } + + if (optind == argc) + fatal("grammar file not specified"); + else + infile = argv[optind]; + + if (optind < argc - 1) + fprintf(stderr, "bison: warning: extra arguments ignored\n"); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/getopt.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/getopt.c:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/getopt.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,491 ---- + /* Getopt for GNU. + Copyright (C) 1987 Free Software Foundation, Inc. + + NO WARRANTY + + BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY + NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW. EXCEPT + WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC, + RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS" + WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY + AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE + DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR + CORRECTION. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M. + STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY + WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE + LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR + OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE + USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR + DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR + A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS + PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH + DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY. + + GENERAL PUBLIC LICENSE TO COPY + + 1. You may copy and distribute verbatim copies of this source file + as you receive it, in any medium, provided that you conspicuously and + appropriately publish on each copy a valid copyright notice "Copyright + (C) 1987 Free Software Foundation, Inc."; and include following the + copyright notice a verbatim copy of the above disclaimer of warranty + and of this License. You may charge a distribution fee for the + physical act of transferring a copy. + + 2. You may modify your copy or copies of this source file or + any portion of it, and copy and distribute such modifications under + the terms of Paragraph 1 above, provided that you also do the following: + + a) cause the modified files to carry prominent notices stating + that you changed the files and the date of any change; and + + b) cause the whole of any work that you distribute or publish, + that in whole or in part contains or is a derivative of this + program or any part thereof, to be licensed at no charge to all + third parties on terms identical to those contained in this + License Agreement (except that you may choose to grant more + extensive warranty protection to third parties, at your option). + + c) You may charge a distribution fee for the physical act of + transferring a copy, and you may at your option offer warranty + protection in exchange for a fee. + + 3. You may copy and distribute this program or any portion of it in + compiled, executable or object code form under the terms of Paragraphs + 1 and 2 above provided that you do the following: + + a) cause each such copy to be accompanied by the + corresponding machine-readable source code, which must + be distributed under the terms of Paragraphs 1 and 2 above; or, + + b) cause each such copy to be accompanied by a + written offer, with no time limit, to give any third party + free (except for a nominal shipping charge) a machine readable + copy of the corresponding source code, to be distributed + under the terms of Paragraphs 1 and 2 above; or, + + c) in the case of a recipient of this program in compiled, executable + or object code form (without the corresponding source code) you + shall cause copies you distribute to be accompanied by a copy + of the written offer of source code which you received along + with the copy you received. + + 4. You may not copy, sublicense, distribute or transfer this program + except as expressly provided under this License Agreement. Any attempt + otherwise to copy, sublicense, distribute or transfer this program is void and + your rights to use the program under this License agreement shall be + automatically terminated. However, parties who have received computer + software programs from you with this License Agreement will not have + their licenses terminated so long as such parties remain in full compliance. + + 5. If you wish to incorporate parts of this program into other free + programs whose distribution conditions are different, write to the Free + Software Foundation at 675 Mass Ave, Cambridge, MA 02139. We have not yet + worked out a simple rule that can be stated here, but we will often permit + this. We will be guided by the two goals of preserving the free status of + all derivatives of our free software and of promoting the sharing and reuse of + software. + + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* This version of `getopt' appears to the caller like standard Unix `getopt' + but it behaves differently for the user, since it allows the user + to intersperse the options with the other arguments. + + As `getopt' works, it permutes the elements of `argv' so that, + when it is done, all the options precede everything else. Thus + all application programs are extended to handle flexible argument order. + + Setting the environment variable _POSIX_OPTION_ORDER disables permutation. + Then the behavior is completely standard. + + GNU application programs can use a third alternative mode in which + they can distinguish the relative order of options and other arguments. */ + + #include + #include + #include + + #ifdef sparc + #include + #endif + + #define alloca1(x) malloc(x) + #ifndef bcopy + #define bcopy(src, dst, num) memcpy((dst), (src), (num)) + #endif + + /* For communication from `getopt' to the caller. + When `getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + + char *optarg = 0; + + /* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `getopt'. + + On entry to `getopt', zero means this is the first call; initialize. + + When `getopt' returns EOF, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + + int optind = 0; + + /* The next char to be scanned in the option-element + in which the last option character we returned was found. + This allows us to pick up the scan where we left off. + + If this is zero, or a null string, it means resume the scan + by advancing to the next ARGV-element. */ + + static char *nextchar; + + /* Callers store zero here to inhibit the error message + for unrecognized options. */ + + int opterr = 1; + + /* Describe how to deal with options that follow non-option ARGV-elements. + + UNSPECIFIED means the caller did not specify anything; + the default is then REQUIRE_ORDER if the environment variable + _OPTIONS_FIRST is defined, PERMUTE otherwise. + + REQUIRE_ORDER means don't recognize them as options. + Stop option processing when the first non-option is seen. + This is what Unix does. + + PERMUTE is the default. We permute the contents of `argv' as we scan, + so that eventually all the options are at the end. This allows options + to be given in any order, even with programs that were not written to + expect this. + + RETURN_IN_ORDER is an option available to programs that were written + to expect options and other ARGV-elements in any order and that care about + the ordering of the two. We describe each non-option ARGV-element + as if it were the argument of an option with character code zero. + Using `-' as the first character of the list of option characters + requests this mode of operation. + + The special argument `--' forces an end of option-scanning regardless + of the value of `ordering'. In the case of RETURN_IN_ORDER, only + `--' can cause `getopt' to return EOF with `optind' != ARGC. */ + + static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering; + + /* Handle permutation of arguments. */ + + /* Describe the part of ARGV that contains non-options that have + been skipped. `first_nonopt' is the index in ARGV of the first of them; + `last_nonopt' is the index after the last of them. */ + + static int first_nonopt; + static int last_nonopt; + + /* Exchange two adjacent subsequences of ARGV. + One subsequence is elements [first_nonopt,last_nonopt) + which contains all the non-options that have been skipped so far. + The other is elements [last_nonopt,optind), which contains all + the options processed since those non-options were skipped. + + `first_nonopt' and `last_nonopt' are relocated so that they describe + the new indices of the non-options in ARGV after they are moved. */ + + static void exchange(char **argv) + { + int nonopts_size + = (last_nonopt - first_nonopt) * sizeof (char *); + char **temp = (char **) alloca1 (nonopts_size); + + /* Interchange the two blocks of data in argv. */ + + bcopy (&argv[first_nonopt], temp, nonopts_size); + bcopy (&argv[last_nonopt], &argv[first_nonopt], + (optind - last_nonopt) * sizeof (char *)); + bcopy (temp, &argv[first_nonopt + optind - last_nonopt], + nonopts_size); + + /* Update records for the slots the non-options now occupy. */ + + first_nonopt += (optind - last_nonopt); + last_nonopt = optind; + } + + /* Scan elements of ARGV (whose length is ARGC) for option characters + given in OPTSTRING. + + If an element of ARGV starts with '-', and is not exactly "-" or "--", + then it is an option element. The characters of this element + (aside from the initial '-') are option characters. If `getopt' + is called repeatedly, it returns successively each of theoption characters + from each of the option elements. + + If `getopt' finds another option character, it returns that character, + updating `optind' and `nextchar' so that the next call to `getopt' can + resume the scan with the following option character or ARGV-element. + + If there are no more option characters, `getopt' returns `EOF'. + Then `optind' is the index in ARGV of the first ARGV-element + that is not an option. (The ARGV-elements have been permuted + so that those that are not options now come last.) + + OPTSTRING is a string containing the legitimate option characters. + A colon in OPTSTRING means that the previous character is an option + that wants an argument. The argument is taken from the rest of the + current ARGV-element, or from the following ARGV-element, + and returned in `optarg'. + + If an option character is seen that is not listed in OPTSTRING, + return '?' after printing an error message. If you set `opterr' to + zero, the error message is suppressed but we still return '?'. + + If a char in OPTSTRING is followed by a colon, that means it wants an arg, + so the following text in the same ARGV-element, or the text of the following + ARGV-element, is returned in `optarg. Two colons mean an option that + wants an optional arg; if there is text in the current ARGV-element, + it is returned in `optarg'. + + If OPTSTRING starts with `-', it requests a different method of handling the + non-option ARGV-elements. See the comments about RETURN_IN_ORDER, above. + */ + + int getopt(int argc,char **argv,char *optstring) + { + /* Initialize the internal data when the first call is made. + Start processing options with ARGV-element 1 (since ARGV-element 0 + is the program name); the sequence of previously skipped + non-option ARGV-elements is empty. */ + + if (optind == 0) + { + first_nonopt = last_nonopt = optind = 1; + + nextchar = 0; + + /* Determine how to handle the ordering of options and nonoptions. */ + + if (optstring[0] == '-') + ordering = RETURN_IN_ORDER; + else if (getenv ("_POSIX_OPTION_ORDER") != 0) + ordering = REQUIRE_ORDER; + else + ordering = PERMUTE; + } + + if (nextchar == 0 || *nextchar == 0) + { + if (ordering == PERMUTE) + { + /* If we have just processed some options following some non-options, + exchange them so that the options come first. */ + + if (first_nonopt != last_nonopt && last_nonopt != optind) + exchange (argv); + else if (last_nonopt != optind) + first_nonopt = optind; + + /* Now skip any additional non-options + and extend the range of non-options previously skipped. */ + + while (optind < argc + && (argv[optind][0] != '-' + || argv[optind][1] == 0)) + optind++; + last_nonopt = optind; + } + + /* Special ARGV-element `--' means premature end of options. + Skip it like a null option, + then exchange with previous non-options as if it were an option, + then skip everything else like a non-option. */ + + if (optind != argc && !strcmp (argv[optind], "--")) + { + optind++; + + if (first_nonopt != last_nonopt && last_nonopt != optind) + exchange (argv); + else if (first_nonopt == last_nonopt) + first_nonopt = optind; + last_nonopt = argc; + + optind = argc; + } + + /* If we have done all the ARGV-elements, stop the scan + and back over any non-options that we skipped and permuted. */ + + if (optind == argc) + { + /* Set the next-arg-index to point at the non-options + that we previously skipped, so the caller will digest them. */ + if (first_nonopt != last_nonopt) + optind = first_nonopt; + return EOF; + } + + /* If we have come to a non-option and did not permute it, + either stop the scan or describe it to the caller and pass it by. */ + + if (argv[optind][0] != '-' || argv[optind][1] == 0) + { + if (ordering == REQUIRE_ORDER) + return EOF; + optarg = argv[optind++]; + return 0; + } + + /* We have found another option-ARGV-element. + Start decoding its characters. */ + + nextchar = argv[optind] + 1; + } + + /* Look at and handle the next option-character. */ + + { + char c = *nextchar++; + + /* This is only supported with 'cc' + char *temp = (char *) index (optstring, c); + */ + + char *temp = strchr(optstring, (int) c); + + /* Increment `optind' when we start to process its last character. */ + if (*nextchar == 0) + optind++; + + if (temp == 0 || c == ':') + { + if (opterr != 0) + { + if (c < 040 || c >= 0177) + fprintf (stderr, "%s: unrecognized option, character code 0%o\n", + argv[0], c); + else + fprintf (stderr, "%s: unrecognized option `-%c'\n", + argv[0], c); + } + return '?'; + } + if (temp[1] == ':') + { + if (temp[2] == ':') + { + /* This is an option that accepts an argument optionally. */ + if (*nextchar != 0) + { + optarg = nextchar; + optind++; + } + else + optarg = 0; + nextchar = 0; + } + else + { + /* This is an option that requires an argument. */ + if (*nextchar != 0) + { + optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + optind++; + } + else if (optind == argc) + { + if (opterr != 0) + fprintf (stderr, "%s: no argument for `-%c' option\n", + argv[0], c); + optarg = 0; + } + else + /* We already incremented `optind' once; + increment it again when taking next ARGV-elt as argument. */ + optarg = argv[optind++]; + nextchar = 0; + } + } + return c; + } + } + + #ifdef TEST + + /* Compile with -DTEST to make an executable for use in testing + the above definition of `getopt'. */ + + int main(int argc,char **argv) + { + char c; + int digit_optind = 0; + + while (1) + { + int this_option_optind = optind; + if ((c = getopt (argc, argv, "abc:d:0123456789")) == EOF) + break; + + switch (c) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (digit_optind != 0 && digit_optind != this_option_optind) + printf ("digits occur in two different argv-elements.\n"); + digit_optind = this_option_optind; + printf ("option %c\n", c); + break; + + case 'a': + printf ("option a\n"); + break; + + case 'b': + printf ("option b\n"); + break; + + case 'c': + printf ("option c with value `%s'\n", optarg); + break; + + case '?': + break; + + default: + printf ("?? getopt returned character code 0%o ??\n", c); + } + } + + if (optind < argc) + { + printf ("non-option ARGV-elements: "); + while (optind < argc) + printf ("%s ", argv[optind++]); + printf ("\n"); + } + + return 0; + } + + #endif /* TEST */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/gram.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/gram.c:1.1 *** /dev/null Tue Oct 5 13:32:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/gram.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,49 ---- + /* Allocate input grammar variables for bison, + Copyright (C) 1984, 1986 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* comments for these variables are in gram.h */ + + int nitems; + int nrules; + int nsyms; + int ntokens; + int nvars; + + short *ritem; + short *rlhs; + short *rrhs; + short *rprec; + short *sprec; + short *rassoc; + short *sassoc; + short *token_translations; + short *rline; + + int start_symbol; + + int translations; + + int max_user_token_number; + + int semantic_parser; + + int pure_parser; + + int error_token_number; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/gram.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/gram.h:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/gram.h Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,111 ---- + /* Data definitions for internal representation of bison's input, + Copyright (C) 1984, 1986 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* representation of the grammar rules: + + ntokens is the number of tokens, and nvars is the number of variables (nonterminals). + nsyms is the total number, ntokens + nvars. + + Each symbol (either token or variable) receives a symbol number. + Numbers 0 to ntokens-1 are for tokens, and ntokens to nsyms-1 are for variables. + Symbol number zero is the end-of-input token. This token is counted in ntokens. + + The rules receive rule numbers 1 to nrules in the order they are written. + Actions and guards are accessed via the rule number. + + The rules themselves are described by three arrays: rrhs, rlhs and ritems. + rlhs[r] is the symbol number of the left hand side of rule r. + The right hand side is stored as symbol numbers in a portion of ritems. + rrhs[r] contains the index in ritems of the beginning of the portion for rule r. + The length of the portion is one greater + than the number of symbols in the rule's right hand side. + The last element in the portion contains minus r, which + identifies it as the end of a portion and says which rule it is for. + + The portions of ritems come in order of increasing rule number and are + followed by an element which is zero to mark the end. nitems is the + total length of ritems, not counting the final zero. Each element of + ritems is called an "item" and its index in ritems is an item number. + + Item numbers are used in the finite state machine to represent + places that parsing can get to. + + Precedence levels are recorded in the vectors sprec and rprec. + sprec records the precedence level of each symbol, + rprec the precedence level of each rule. + + Precedence levels are assigned in increasing order starting with 1 + so that numerically higher precedence values mean tighter binding + as they ought to. Zero as a symbol or rule's precedence means none is assigned. + + Associativities are recorded similarly in rassoc and sassoc. */ + + + #define ISTOKEN(s) ((s) < ntokens) + #define ISVAR(s) ((s) >= ntokens) + + + extern int nitems; + extern int nrules; + extern int nsyms; + extern int ntokens; + extern int nvars; + + extern short *ritem; + extern short *rlhs; + extern short *rrhs; + extern short *rprec; + extern short *sprec; + extern short *rassoc; + extern short *sassoc; + extern short *rline; /* Source line number of each rule */ + + extern int start_symbol; + + + /* associativity values in elements of rassoc, sassoc. */ + + #define RIGHT_ASSOC 1 + #define LEFT_ASSOC 2 + #define NON_ASSOC 3 + + /* token translation table: + indexed by a token number as returned by the user's yylex routine, + it yields the internal token number used by the parser and throughout bison. + If translations is zero, the translation table is not used because + the two kinds of token numbers are the same. */ + + extern short *token_translations; + extern int translations; + extern int max_user_token_number; + + /* semantic_parser is nonzero if the input file says to use the hairy parser + that provides for semantic error recovery. If it is zero, the yacc-compatible + simplified parser is used. */ + + extern int semantic_parser; + + /* pure_parser is nonzero if should generate a parser that is all pure and reentrant. */ + + extern int pure_parser; + + /* error_token_number is the token number of the error token. */ + + extern int error_token_number; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/lalr.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/lalr.c:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/lalr.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,745 ---- + /* Compute look-ahead criteria for bison, + Copyright (C) 1984, 1986 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* Compute how to make the finite state machine deterministic; + find which rules need lookahead in each state, and which lookahead tokens they accept. + + lalr(), the entry point, builds these data structures: + + goto_map, from_state and to_state + record each shift transition which accepts a variable (a nonterminal). + ngotos is the number of such transitions. + from_state[t] is the state number which a transition leads from + and to_state[t] is the state number it leads to. + All the transitions that accept a particular variable are grouped together and + goto_map[i - ntokens] is the index in from_state and to_state of the first of them. + + consistent[s] is nonzero if no lookahead is needed to decide what to do in state s. + + LAruleno is a vector which records the rules that need lookahead in various states. + The elements of LAruleno that apply to state s are those from + lookaheads[s] through lookaheads[s+1]-1. + Each element of LAruleno is a rule number. + + If lr is the length of LAruleno, then a number from 0 to lr-1 + can specify both a rule and a state where the rule might be applied. + + LA is a lr by ntokens matrix of bits. + LA[l, i] is 1 if the rule LAruleno[l] is applicable in the appropriate state + when the next token is symbol i. + If LA[l, i] and LA[l, j] are both 1 for i != j, it is a conflict. + */ + + #include + #include "machine.h" + #include "types.h" + #include "state.h" + #include "new.h" + #include "gram.h" + + + extern short **derives; + extern char *nullable; + + + int tokensetsize; + short *lookaheads; + short *LAruleno; + unsigned *LA; + short *accessing_symbol; + char *consistent; + core **state_table; + shifts **shift_table; + reductions **reduction_table; + short *goto_map; + short *from_state; + short *to_state; + + short **transpose(); + + + static int infinity; + static int maxrhs; + static int ngotos; + static unsigned *F; + static short **includes; + static shorts **lookback; + static short **R; + static short *INDEX; + static short *VERTICES; + static int top; + + extern void toomany(char *s); + extern void berror(char *s); + + void set_state_table(void); + void set_accessing_symbol(void); + void set_shift_table(void); + void set_reduction_table(void); + void set_maxrhs(void); + void initialize_LA(void); + void set_goto_map(void); + void initialize_F(void); + void build_relations(void); + void compute_FOLLOWS(void); + void compute_lookaheads(void); + void digraph(short **relation); + void add_lookback_edge(int stateno,int ruleno,int gotono); + void traverse(register int i); + + void lalr(void) + { + tokensetsize = WORDSIZE(ntokens); + + set_state_table(); + set_accessing_symbol(); + set_shift_table(); + set_reduction_table(); + set_maxrhs(); + initialize_LA(); + set_goto_map(); + initialize_F(); + build_relations(); + compute_FOLLOWS(); + compute_lookaheads(); + } + + + + void set_state_table(void) + { + register core *sp; + + state_table = NEW2(nstates, core *); + + for (sp = first_state; sp; sp = sp->next) + state_table[sp->number] = sp; + } + + + + void set_accessing_symbol(void) + { + register core *sp; + + accessing_symbol = NEW2(nstates, short); + + for (sp = first_state; sp; sp = sp->next) + accessing_symbol[sp->number] = sp->accessing_symbol; + } + + + + void set_shift_table(void) + { + register shifts *sp; + + shift_table = NEW2(nstates, shifts *); + + for (sp = first_shift; sp; sp = sp->next) + shift_table[sp->number] = sp; + } + + + + void set_reduction_table(void) + { + register reductions *rp; + + reduction_table = NEW2(nstates, reductions *); + + for (rp = first_reduction; rp; rp = rp->next) + reduction_table[rp->number] = rp; + } + + + + void set_maxrhs(void) + { + register short *itemp; + register int length; + register int max; + + length = 0; + max = 0; + for (itemp = ritem; *itemp; itemp++) + { + if (*itemp > 0) + { + length++; + } + else + { + if (length > max) max = length; + length = 0; + } + } + + maxrhs = max; + } + + + + void initialize_LA(void) + { + register int i; + register int j; + register int count; + register reductions *rp; + register shifts *sp; + register short *np; + + consistent = NEW2(nstates, char); + lookaheads = NEW2(nstates + 1, short); + + count = 0; + for (i = 0; i < nstates; i++) + { + register int j; + + lookaheads[i] = count; + + rp = reduction_table[i]; + sp = shift_table[i]; + if (rp && (rp->nreds > 1 + || (sp && ! ISVAR(accessing_symbol[sp->shifts[0]])))) + count += rp->nreds; + else + consistent[i] = 1; + + if (sp) + for (j = 0; j < sp->nshifts; j++) + { + if (accessing_symbol[sp->shifts[j]] == error_token_number) + { + consistent[i] = 0; + break; + } + } + } + + lookaheads[nstates] = count; + + LA = NEW2(count * tokensetsize, unsigned); + LAruleno = NEW2(count, short); + lookback = NEW2(count, shorts *); + + np = LAruleno; + for (i = 0; i < nstates; i++) + { + if (!consistent[i]) + { + if (rp = reduction_table[i]) + for (j = 0; j < rp->nreds; j++) + *np++ = rp->rules[j]; + } + } + } + + + + void set_goto_map(void) + { + register shifts *sp; + register int i; + register int symbol; + register int k; + register short *temp_map; + register int state2; + register int state1; + + goto_map = NEW2(nvars + 1, short) - ntokens; + temp_map = NEW2(nvars + 1, short) - ntokens; + + ngotos = 0; + for (sp = first_shift; sp; sp = sp->next) + { + for (i = sp->nshifts - 1; i >= 0; i--) + { + symbol = accessing_symbol[sp->shifts[i]]; + + if (ISTOKEN(symbol)) break; + + if (ngotos == MAXSHORT) + toomany("gotos"); + + ngotos++; + goto_map[symbol]++; + } + } + + k = 0; + for (i = ntokens; i < nsyms; i++) + { + temp_map[i] = k; + k += goto_map[i]; + } + + for (i = ntokens; i < nsyms; i++) + goto_map[i] = temp_map[i]; + + goto_map[nsyms] = ngotos; + temp_map[nsyms] = ngotos; + + from_state = NEW2(ngotos, short); + to_state = NEW2(ngotos, short); + + for (sp = first_shift; sp; sp = sp->next) + { + state1 = sp->number; + for (i = sp->nshifts - 1; i >= 0; i--) + { + state2 = sp->shifts[i]; + symbol = accessing_symbol[state2]; + + if (ISTOKEN(symbol)) break; + + k = temp_map[symbol]++; + from_state[k] = state1; + to_state[k] = state2; + } + } + + FREE(temp_map + ntokens); + } + + + + /* Map_goto maps a state/symbol pair into its numeric representation. */ + + int map_goto(int state,int symbol) + { + register int high; + register int low; + register int middle; + register int s; + + low = goto_map[symbol]; + high = goto_map[symbol + 1]; + + while (low <= high) + { + middle = (low + high) / 2; + s = from_state[middle]; + if (s == state) + return (middle); + else if (s < state) + low = middle + 1; + else + high = middle - 1; + } + + berror("map_goto"); + + /* NOTREACHED */ + } + + + + void initialize_F(void) + { + register int i; + register int j; + register int k; + register shifts *sp; + register short *edge; + register unsigned *rowp; + register short *rp; + register short **reads; + register int nedges; + register int stateno; + register int symbol; + register int nwords; + + nwords = ngotos * tokensetsize; + F = NEW2(nwords, unsigned); + + reads = NEW2(ngotos, short *); + edge = NEW2(ngotos + 1, short); + nedges = 0; + + rowp = F; + for (i = 0; i < ngotos; i++) + { + stateno = to_state[i]; + sp = shift_table[stateno]; + + if (sp) + { + k = sp->nshifts; + + for (j = 0; j < k; j++) + { + symbol = accessing_symbol[sp->shifts[j]]; + if (ISVAR(symbol)) + break; + SETBIT(rowp, symbol); + } + + for (; j < k; j++) + { + symbol = accessing_symbol[sp->shifts[j]]; + if (nullable[symbol]) + edge[nedges++] = map_goto(stateno, symbol); + } + + if (nedges) + { + reads[i] = rp = NEW2(nedges + 1, short); + + for (j = 0; j < nedges; j++) + rp[j] = edge[j]; + + rp[nedges] = -1; + nedges = 0; + } + } + + rowp += tokensetsize; + } + + digraph(reads); + + for (i = 0; i < ngotos; i++) + { + if (reads[i]) + FREE(reads[i]); + } + + FREE(reads); + FREE(edge); + } + + void build_relations(void) + { + register int i; + register int j; + register int k; + register short *rulep; + register short *rp; + register shifts *sp; + register int length; + register int nedges; + register int done; + register int state1; + register int stateno; + register int symbol1; + register int symbol2; + register short *shortp; + register short *edge; + register short *states; + register short **new_includes; + + includes = NEW2(ngotos, short *); + edge = NEW2(ngotos + 1, short); + states = NEW2(maxrhs + 1, short); + + for (i = 0; i < ngotos; i++) + { + nedges = 0; + state1 = from_state[i]; + symbol1 = accessing_symbol[to_state[i]]; + + for (rulep = derives[symbol1]; *rulep > 0; rulep++) + { + length = 1; + states[0] = state1; + stateno = state1; + + for (rp = ritem + rrhs[*rulep]; *rp > 0; rp++) + { + symbol2 = *rp; + sp = shift_table[stateno]; + k = sp->nshifts; + + for (j = 0; j < k; j++) + { + stateno = sp->shifts[j]; + if (accessing_symbol[stateno] == symbol2) break; + } + + states[length++] = stateno; + } + + if (!consistent[stateno]) + add_lookback_edge(stateno, *rulep, i); + + length--; + done = 0; + while (!done) + { + done = 1; + rp--; + /* JF added rp>=ritem && I hope to god its right! */ + if (rp>=ritem && ISVAR(*rp)) + { + stateno = states[--length]; + edge[nedges++] = map_goto(stateno, *rp); + if (nullable[*rp]) done = 0; + } + } + } + + if (nedges) + { + includes[i] = shortp = NEW2(nedges + 1, short); + for (j = 0; j < nedges; j++) + shortp[j] = edge[j]; + shortp[nedges] = -1; + } + } + + new_includes = transpose(includes, ngotos); + + for (i = 0; i < ngotos; i++) + if (includes[i]) + FREE(includes[i]); + + FREE(includes); + + includes = new_includes; + + FREE(edge); + FREE(states); + } + + + + void add_lookback_edge(int stateno,int ruleno,int gotono) + { + register int i; + register int k; + register int found; + register shorts *sp; + + i = lookaheads[stateno]; + k = lookaheads[stateno + 1]; + found = 0; + while (!found && i < k) + { + if (LAruleno[i] == ruleno) + found = 1; + else + i++; + } + + if (found == 0) + berror("add_lookback_edge"); + + sp = NEW(shorts); + sp->next = lookback[i]; + sp->value = gotono; + lookback[i] = sp; + } + + + + short **transpose(short **R,int n) + { + register short **new_R; + register short **temp_R; + register short *nedges; + register short *sp; + register int i; + register int k; + + nedges = NEW2(n, short); + + for (i = 0; i < n; i++) + { + sp = R[i]; + if (sp) + { + while (*sp >= 0) + nedges[*sp++]++; + } + } + + new_R = NEW2(n, short *); + temp_R = NEW2(n, short *); + + for (i = 0; i < n; i++) + { + k = nedges[i]; + if (k > 0) + { + sp = NEW2(k + 1, short); + new_R[i] = sp; + temp_R[i] = sp; + sp[k] = -1; + } + } + + FREE(nedges); + + for (i = 0; i < n; i++) + { + sp = R[i]; + if (sp) + { + while (*sp >= 0) + *temp_R[*sp++]++ = i; + } + } + + FREE(temp_R); + + return (new_R); + } + + + + void compute_FOLLOWS(void) + { + register int i; + + digraph(includes); + + for (i = 0; i < ngotos; i++) + { + if (includes[i]) FREE(includes[i]); + } + + FREE(includes); + } + + + + void compute_lookaheads(void) + { + register int i; + register int n; + register unsigned *fp1; + register unsigned *fp2; + register unsigned *fp3; + register shorts *sp; + register unsigned *rowp; + /* register short *rulep; JF unused */ + /* register int count; JF unused */ + register shorts *sptmp;/* JF */ + + rowp = LA; + n = lookaheads[nstates]; + for (i = 0; i < n; i++) + { + fp3 = rowp + tokensetsize; + for (sp = lookback[i]; sp; sp = sp->next) + { + fp1 = rowp; + fp2 = F + tokensetsize * sp->value; + while (fp1 < fp3) + *fp1++ |= *fp2++; + } + + rowp = fp3; + } + + for (i = 0; i < n; i++) + {/* JF removed ref to freed storage */ + for (sp = lookback[i]; sp; sp = sptmp) { + sptmp=sp->next; + FREE(sp); + } + } + + FREE(lookback); + FREE(F); + } + + + + void digraph(short **relation) + { + register int i; + + infinity = ngotos + 2; + INDEX = NEW2(ngotos + 1, short); + VERTICES = NEW2(ngotos + 1, short); + top = 0; + + R = relation; + + for (i = 0; i < ngotos; i++) + INDEX[i] = 0; + + for (i = 0; i < ngotos; i++) + { + if (INDEX[i] == 0 && R[i]) + traverse(i); + } + + FREE(INDEX); + FREE(VERTICES); + } + + void traverse(register int i) + { + register unsigned *fp1; + register unsigned *fp2; + register unsigned *fp3; + register int j; + register short *rp; + + int height; + unsigned *base; + + VERTICES[++top] = i; + INDEX[i] = height = top; + + base = F + i * tokensetsize; + fp3 = base + tokensetsize; + + rp = R[i]; + if (rp) + { + while ((j = *rp++) >= 0) + { + if (INDEX[j] == 0) + traverse(j); + + if (INDEX[i] > INDEX[j]) + INDEX[i] = INDEX[j]; + + fp1 = base; + fp2 = F + j * tokensetsize; + + while (fp1 < fp3) + *fp1++ |= *fp2++; + } + } + + if (INDEX[i] == height) + { + for (;;) + { + j = VERTICES[top--]; + INDEX[j] = infinity; + + if (i == j) + break; + + fp1 = base; + fp2 = F + j * tokensetsize; + + while (fp1 < fp3) + *fp2++ = *fp1++; + } + } + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/lex.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/lex.c:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/lex.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,440 ---- + /* Token-reader for Bison's input parser, + Copyright (C) 1984, 1986 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* + lex() is the entry point. It is called from reader.c. + It returns one of the token-type codes defined in lex.h. + When an identifier is seen, the code IDENTIFIER is returned + and the name is looked up in the symbol table using symtab.c; + symval is set to a pointer to the entry found. */ + + #include + #include + #include "files.h" + #include "symtab.h" + #include "lex.h" + + + extern int lineno; + extern int translations; + + + char token_buffer[MAXTOKEN + 1]; + bucket *symval; + int numval; + + static int unlexed; /* these two describe a token to be reread */ + static bucket *unlexed_symval; /* by the next call to lex */ + + extern void fatals(char *fmt,int x1,int x2,int x3,int x4,int x5,int x6, + int x7,int x8); + extern void fatal(char *s); + + int parse_percent_token(void); + + void init_lex(void) + { + unlexed = -1; + } + + + + int skip_white_space(void) + { + register int c; + register int inside; + + c = getc(finput); + + for (;;) + { + switch (c) + { + case '/': + c = getc(finput); + if (c != '*') + fatals("unexpected '/%c' found",c,0,0,0,0,0,0,0); + + c = getc(finput); + + inside = 1; + while (inside) + { + if (c == '*') + { + while (c == '*') + c = getc(finput); + + if (c == '/') + { + inside = 0; + c = getc(finput); + } + } + else if (c == '\n') + { + lineno++; + c = getc(finput); + } + else if (c == EOF) + fatal("unterminated comment"); + else + c = getc(finput); + } + + break; + + case '\n': + lineno++; + + case ' ': + case '\t': + case '\f': + c = getc(finput); + break; + + default: + return (c); + } + } + } + + void unlex(int token) + { + unlexed = token; + unlexed_symval = symval; + } + + int lex(void) + { + register int c; + register char *p; + + if (unlexed >= 0) + { + symval = unlexed_symval; + c = unlexed; + unlexed = -1; + return (c); + } + + c = skip_white_space(); + + switch (c) + { + case EOF: + return (ENDFILE); + + case 'A': case 'B': case 'C': case 'D': case 'E': + case 'F': case 'G': case 'H': case 'I': case 'J': + case 'K': case 'L': case 'M': case 'N': case 'O': + case 'P': case 'Q': case 'R': case 'S': case 'T': + case 'U': case 'V': case 'W': case 'X': case 'Y': + case 'Z': + case 'a': case 'b': case 'c': case 'd': case 'e': + case 'f': case 'g': case 'h': case 'i': case 'j': + case 'k': case 'l': case 'm': case 'n': case 'o': + case 'p': case 'q': case 'r': case 's': case 't': + case 'u': case 'v': case 'w': case 'x': case 'y': + case 'z': + case '.': case '_': + p = token_buffer; + while (isalnum(c) || c == '_' || c == '.') + { + if (p < token_buffer + MAXTOKEN) + *p++ = c; + c = getc(finput); + } + + *p = 0; + ungetc(c, finput); + symval = getsym(token_buffer); + return (IDENTIFIER); + + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + { + numval = 0; + + while (isdigit(c)) + { + numval = numval*10 + c - '0'; + c = getc(finput); + } + ungetc(c, finput); + return (NUMBER); + } + + case '\'': + translations = -1; + + /* parse the literal token and compute character code in code */ + + c = getc(finput); + { + register int code = 0; + + if (c == '\\') + { + c = getc(finput); + + if (c <= '7' && c >= '0') + { + while (c <= '7' && c >= '0') + { + code = (code * 8) + (c - '0'); + c = getc(finput); + } + if (code >= 128 || code<0)/* JF this said if(c>=128) */ + fatals("malformatted literal token '\\%03o'",code,0,0,0,0,0, + 0,0); + } + else + { + if (c == 't') + code = '\t'; + else if (c == 'n') + code = '\n'; + else if (c == 'r') + code = '\r'; + else if (c == 'f') + code = '\f'; + else if (c == 'b') + code = '\b'; + else if (c == '\\') + code = '\\'; + else if (c == '\'') + code = '\''; + else if (c == '\"') /* JF this is a good idea */ + code = '\"'; + else fatals("invalid literal token '\\%c'",c,0,0,0,0,0,0,0); + c = getc(finput); + } + } + else + { + code = c; + c = getc(finput); + } + if (c != '\'') + fatal("multicharacter literal tokens NOT supported"); + + /* now fill token_buffer with the canonical name for this character + as a literal token. Do not use what the user typed, + so that '\012' and '\n' can be interchangeable. */ + + p = token_buffer; + *p++ = '\''; + if (code == '\\') + { + p = token_buffer + 1; + *p++ = '\\'; + *p++ = '\\'; + } + else if (code == '\'') + { + p = token_buffer + 1; + *p++ = '\\'; + *p++ = '\''; + } + else if (code >= 040 && code != 0177) + *p++ = code; + else if (code == '\t') + { + p = token_buffer + 1; + *p++ = '\\'; + *p++ = 't'; + } + else if (code == '\n') + { + p = token_buffer + 1; + *p++ = '\\'; + *p++ = 'n'; + } + else if (code == '\r') + { + p = token_buffer + 1; + *p++ = '\\'; + *p++ = 'r'; + } + else if (code == '\b') + { + p = token_buffer + 1; + *p++ = '\\'; + *p++ = 'b'; + } + else if (code == '\f') + { + p = token_buffer + 1; + *p++ = '\\'; + *p++ = 'f'; + } + else + { + *p++ = code / 0100 + '0'; + *p++ = ((code / 010) & 07) + '0'; + *p++ = (code & 07) + '0'; + } + *p++ = '\''; + *p = 0; + symval = getsym(token_buffer); + symval->class = STOKEN; + if (! symval->user_token_number) + symval->user_token_number = code; + return (IDENTIFIER); + } + + case ',': + return (COMMA); + + case ':': + return (COLON); + + case ';': + return (SEMICOLON); + + case '|': + return (BAR); + + case '{': + return (LEFT_CURLY); + + case '=': + do + { + c = getc(finput); + if (c == '\n') lineno++; + } + while(c==' ' || c=='\n' || c=='\t'); + + if (c == '{') + return(LEFT_CURLY); + else + { + ungetc(c, finput); + return(ILLEGAL); + } + + case '<': + p = token_buffer; + c = getc(finput); + while (c != '>') + { + if (c == '\n' || c == EOF) + fatal("unterminated type name"); + + if (p >= token_buffer + MAXTOKEN - 1) + fatals("type name too long (%d max)",MAXTOKEN-1,0,0,0,0,0,0,0); + + *p++ = c; + c = getc(finput); + } + *p = 0; + return (TYPENAME); + + + case '%': + return (parse_percent_token()); + + default: + return (ILLEGAL); + } + } + + + /* parse a token which starts with %. Assumes the % has already been read and discarded. */ + + int parse_percent_token(void) + { + register int c; + register char *p; + + p = token_buffer; + c = getc(finput); + + switch (c) + { + case '%': + return (TWO_PERCENTS); + + case '{': + return (PERCENT_LEFT_CURLY); + + case '<': + return (LEFT); + + case '>': + return (RIGHT); + + case '2': + return (NONASSOC); + + case '0': + return (TOKEN); + + case '=': + return (PREC); + } + if (!isalpha(c)) + return (ILLEGAL); + + while (isalpha(c) || c == '_') + { + if (p < token_buffer + MAXTOKEN) + *p++ = c; + c = getc(finput); + } + + ungetc(c, finput); + + *p = 0; + + if (strcmp(token_buffer, "token") == 0 + || + strcmp(token_buffer, "term") == 0) + return (TOKEN); + else if (strcmp(token_buffer, "nterm") == 0) + return (NTERM); + else if (strcmp(token_buffer, "type") == 0) + return (TYPE); + else if (strcmp(token_buffer, "guard") == 0) + return (GUARD); + else if (strcmp(token_buffer, "union") == 0) + return (UNION); + else if (strcmp(token_buffer, "expect") == 0) + return (EXPECT); + else if (strcmp(token_buffer, "start") == 0) + return (START); + else if (strcmp(token_buffer, "left") == 0) + return (LEFT); + else if (strcmp(token_buffer, "right") == 0) + return (RIGHT); + else if (strcmp(token_buffer, "nonassoc") == 0 + || + strcmp(token_buffer, "binary") == 0) + return (NONASSOC); + else if (strcmp(token_buffer, "semantic_parser") == 0) + return (SEMANTIC_PARSER); + else if (strcmp(token_buffer, "pure_parser") == 0) + return (PURE_PARSER); + else if (strcmp(token_buffer, "prec") == 0) + return (PREC); + else return (ILLEGAL); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/lex.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/lex.h:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/lex.h Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,47 ---- + /* Token type definitions for bison's input reader, + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + #define ENDFILE 0 + #define IDENTIFIER 1 + #define COMMA 2 + #define COLON 3 + #define SEMICOLON 4 + #define BAR 5 + #define LEFT_CURLY 6 + #define TWO_PERCENTS 7 + #define PERCENT_LEFT_CURLY 8 + #define TOKEN 9 + #define NTERM 10 + #define GUARD 11 + #define TYPE 12 + #define UNION 13 + #define START 14 + #define LEFT 15 + #define RIGHT 16 + #define NONASSOC 17 + #define PREC 18 + #define SEMANTIC_PARSER 19 + #define PURE_PARSER 20 + #define TYPENAME 21 + #define NUMBER 22 + #define EXPECT 23 + #define ILLEGAL 24 + + #define MAXTOKEN 1024 Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/machine.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/machine.h:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/machine.h Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,26 ---- + /* Define machine-dependencies for bison, + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + #define MAXSHORT 32767 + #define MINSHORT -32768 + + #define BITS_PER_WORD 32 + #define WORDSIZE(n) (((n) + 31) / 32) + #define SETBIT(x, i) ((x)[(i)>>5] |= (1<<((i) & 31))) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/main.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/main.c:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/main.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,124 ---- + /* Top level entry point of bison, + Copyright (C) 1984, 1986 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + #include + #include "machine.h" /* JF for MAXSHORT */ + + extern int lineno; + extern int verboseflag; + + /* Nonzero means failure has been detected; don't write a parser file. */ + int failure; + + extern void getargs(int argc,char *argv[]); + extern void openfiles(void); + extern void reader(void); + extern void set_derives(void); + extern void set_nullable(void); + extern void generate_states(void); + extern void lalr(void); + extern void initialize_conflicts(void); + extern void verbose(void); + extern void terse(void); + extern void output(void); + extern void done(int k); + + void main(int argc,char *argv[]) + { + failure = 0; + lineno = 0; + getargs(argc, argv); + openfiles(); + + /* read the input. Copy some parts of it to fguard, faction, ftable and fattrs. + In file reader. + The other parts are recorded in the grammar; see gram.h. */ + reader(); + + /* record other info about the grammar. In files derives and nullable. */ + set_derives(); + set_nullable(); + + /* convert to nondeterministic finite state machine. In file LR0. + See state.h for more info. */ + generate_states(); + + /* make it deterministic. In file lalr. */ + lalr(); + + /* Find and record any conflicts: places where one token of lookahead is not + enough to disambiguate the parsing. In file conflicts. + Currently this does not do anything to resolve them; + the trivial form of conflict resolution that exists is done in output. */ + initialize_conflicts(); + + /* print information about results, if requested. In file print. */ + if (verboseflag) + verbose(); + else + terse(); + + /* output the tables and the parser to ftable. In file output. */ + output(); + done(failure); + } + + /* functions to report errors which prevent a parser from being generated */ + + void fatal(char *s) + { + extern char *infile; + + if (infile == 0) + fprintf(stderr, "fatal error: %s\n", s); + else + fprintf(stderr, "\"%s\", line %d: %s\n", infile, lineno, s); + done(1); + } + + + /* JF changed to accept/deal with variable args. Is a real kludge since + we don't support _doprnt calls */ + /*VARARGS1*/ + + void fatals(char *fmt,int x1,int x2,int x3,int x4,int x5,int x6,int x7,int x8) + { + char buffer[200]; + + sprintf(buffer, fmt, x1,x2,x3,x4,x5,x6,x7,x8); + fatal(buffer); + } + + + + void toomany(char *s) + { + char buffer[200]; + + /* JF new msg */ + sprintf(buffer, "limit of %d exceeded, too many %s", MAXSHORT, s); + fatal(buffer); + } + + void berror(char *s) + { + fprintf(stderr, "internal error, %s\n", s); + abort(); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/new.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/new.h:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/new.h Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,42 ---- + /* Storage allocation interface for bison, + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + #include + + #define NEW(t) ((t *) mallocate((unsigned) sizeof(t))) + #define NEW2(n, t) ((t *) mallocate((unsigned) ((n) * sizeof(t)))) + + /* #define FREE(x) (x && free((char *) (x))) + */ + + #define FREE(x) {if (x) free(x);} + + /* + void FREE(void *temp) + { + if (temp) + free(temp); + } + */ + + extern char *mallocate(); + + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/nullable.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/nullable.c:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/nullable.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,128 ---- + /* Part of the bison parser generator, + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* set up nullable, a vector saying which nonterminals can expand into the null string. + nullable[i - ntokens] is nonzero if symbol i can do so. */ + + #include + #include "types.h" + #include "gram.h" + #include "new.h" + + + char *nullable; + + void set_nullable(void) + { + register short *r; + register short *s1; + register short *s2; + register int ruleno; + register int symbol; + register shorts *p; + + short *squeue; + short *rcount; + shorts **rsets; + shorts *relts; + char any_tokens; + short *r1; + + #ifdef TRACE + fprintf(stderr, "Entering set_nullable"); + #endif + + nullable = NEW2(nvars, char) - ntokens; + + squeue = NEW2(nvars, short); + s1 = s2 = squeue; + + rcount = NEW2(nrules + 1, short); + rsets = NEW2(nvars, shorts *) - ntokens; + relts = NEW2(nitems + nvars + 1, shorts); + p = relts; + + r = ritem; + while (*r) + { + if (*r < 0) + { + symbol = rlhs[-(*r++)]; + if (!nullable[symbol]) + { + nullable[symbol] = 1; + *s2++ = symbol; + } + } + else + { + r1 = r; + any_tokens = 0; + for (symbol = *r++; symbol > 0; symbol = *r++) + { + if (ISTOKEN(symbol)) + any_tokens = 1; + } + + if (!any_tokens) + { + ruleno = -symbol; + r = r1; + for (symbol = *r++; symbol > 0; symbol = *r++) + { + rcount[ruleno]++; + p->next = rsets[symbol]; + p->value = ruleno; + rsets[symbol] = p; + p++; + } + } + } + } + + while (s1 < s2) + { + p = rsets[*s1++]; + while (p) + { + ruleno = p->value; + p = p->next; + if (--rcount[ruleno] == 0) + { + symbol = rlhs[ruleno]; + if (!nullable[symbol]) + { + nullable[symbol] = 1; + *s2++ = symbol; + } + } + } + } + + FREE(squeue); + FREE(rcount); + FREE(rsets + ntokens); + FREE(relts); + } + + void free_nullable(void) + { + FREE(nullable + ntokens); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/output.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/output.c:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/output.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,1345 ---- + /* Output the generated parsing program for bison, + Copyright (C) 1984, 1986 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* functions to output parsing data to various files. Entries are: + + output_headers () + + Output constant strings to the beginning of certain files. + + output_trailers() + + Output constant strings to the ends of certain files. + + output () + + Output the parsing tables and the parser code to ftable. + + The parser tables consist of: (starred ones needed only for the semantic parser) + + yytranslate = vector mapping yylex's token numbers into bison's token numbers. + + yytname = vector of string-names indexed by bison token number + + yyrline = vector of line-numbers of all rules. For yydebug printouts. + + * yyrhs = vector of items of all rules. + This is exactly what ritems contains. + + * yyprhs[r] = index in yyrhs of first item for rule r. + + yyr1[r] = symbol number of symbol that rule r derives. + + yyr2[r] = number of symbols composing right hand side of rule r. + + * yystos[s] = the symbol number of the symbol that leads to state s. + + yydefact[s] = default rule to reduce with in state s, + when yytable doesn't specify something else to do. + Zero means the default is an error. + + yydefgoto[i] = default state to go to after a reduction of a rule that + generates variable ntokens + i, except when yytable + specifies something else to do. + + yypact[s] = index in yytable of the portion describing state s. + The lookahed token's type is used to index that portion + to find out what to do. + + If the value in yytable is positive, + we shift the token and go to that state. + + If the value is negative, it is minus a rule number to reduce by. + + If the value is zero, the default action from yydefact[s] is used. + + yypgoto[i] = the index in yytable of the portion describing + what to do after reducing a rule that derives variable i + ntokens. + This portion is indexed by the parser state number + as of before the text for this nonterminal was read. + The value from yytable is the state to go to. + + yytable = a vector filled with portions for different uses, + found via yypact and yypgoto. + + yycheck = a vector indexed in parallel with yytable. + It indicates, in a roundabout way, the bounds of the + portion you are trying to examine. + + Suppose that the portion of yytable starts at index p + and the index to be examined within the portion is i. + Then if yycheck[p+i] != i, i is outside the bounds + of what is actually allocated, and the default + (from yydefact or yydefgoto) should be used. + Otherwise, yytable[p+i] should be used. + + YYFINAL = the state number of the termination state. + YYFLAG = most negative short int. Used to flag ?? + YYNTBASE = ntokens. + + */ + + #include + #include "machine.h" + #include "new.h" + #include "files.h" + #include "gram.h" + #include "state.h" + + #define MAXTABLE 32767 + + + extern int debugflag; + extern int nolinesflag; + + extern char **tags; + extern int tokensetsize; + extern int final_state; + extern core **state_table; + extern shifts **shift_table; + extern errs **err_table; + extern reductions **reduction_table; + extern short *accessing_symbol; + extern unsigned *LA; + extern short *LAruleno; + extern short *lookaheads; + extern char *consistent; + extern short *goto_map; + extern short *from_state; + extern short *to_state; + + + static int nvectors; + static int nentries; + static short **froms; + static short **tos; + static short *tally; + static short *width; + static short *actrow; + static short *state_count; + static short *order; + static short *base; + static short *pos; + static short *table; + static short *check; + static int lowzero; + static int high; + + + + #define GUARDSTR "\n#include \"%s\"\nextern int yyerror;\n\ + extern int yycost;\nextern char * yymsg;\nextern YYSTYPE yyval;\n\n\ + yyguard(n, yyvsp, yylsp)\nregister int n;\nregister YYSTYPE *yyvsp;\n\ + register YYLTYPE *yylsp;\n\ + {\n yyerror = 0;\nyycost = 0;\n yymsg = 0;\nswitch (n)\n {" + + #define ACTSTR "\n#include \"%s\"\nextern YYSTYPE yyval;\ + \nextern int yychar;\ + yyaction(n, yyvsp, yylsp)\nregister int n;\nregister YYSTYPE *yyvsp;\n\ + register YYLTYPE *yylsp;\n{\n switch (n)\n{" + + #define ACTSTR_SIMPLE "\n switch (yyn) {\n" + + extern void berror(char *s); + extern void fatals(char *fmt,int x1,int x2,int x3,int x4,int x5,int x6, + int x7,int x8); + + void free_itemsets(void); + void output_defines(void); + void output_token_translations(void); + void output_gram(void); + void output_stos(void); + void output_rule_data(void); + void output_actions(void); + void output_parser(void); + void output_program(void); + void token_actions(void); + void free_shifts(void); + void free_reductions(void); + void goto_actions(void); + void sort_actions(void); + void pack_table(void); + void output_base(void); + void output_table(void); + void output_check(void); + int action_row(int state); + void save_row(int state); + int default_goto(int symbol); + void save_column(int symbol,int default_state); + int matching_state(int vector); + int pack_vector(int vector); + + + void output_headers(void) + { + if (semantic_parser) + fprintf(fguard, GUARDSTR, attrsfile); + fprintf(faction, (semantic_parser ? ACTSTR : ACTSTR_SIMPLE), attrsfile); + /* if (semantic_parser) JF moved this below + fprintf(ftable, "#include \"%s\"\n", attrsfile); + fprintf(ftable, "#include \n\n"); */ + } + + void output_trailers(void) + { + if (semantic_parser) + { + fprintf(fguard, "\n }\n}\n"); + fprintf(faction, "\n }\n}\n"); + } + else + fprintf(faction, "\n}\n"); + } + + + void output(void) + { + int c; + + /* output_token_defines(ftable); JF put out token defines FIRST */ + if (!semantic_parser) /* JF Put out other stuff */ + { + rewind(fattrs); + while ((c=getc(fattrs))!=EOF) + putc(c,ftable); + } + + if (debugflag) + fprintf(ftable, "#define YYDEBUG\n"); + + if (semantic_parser) + fprintf(ftable, "#include \"%s\"\n", attrsfile); + fprintf(ftable, "#include \n\n"); + + /* Make "const" do nothing if not in ANSI C. */ + fprintf (ftable, "#ifndef __STDC__\n#define const\n#endif\n\n"); + + free_itemsets(); + output_defines(); + output_token_translations(); + if (semantic_parser) + output_gram(); + FREE(ritem); + if (semantic_parser) + output_stos(); + output_rule_data(); + output_actions(); + output_parser(); + output_program(); + } + + void output_token_translations(void) + { + register int i, j; + /* register short *sp; JF unused */ + + if (translations) + { + fprintf(ftable, + "\n#define YYTRANSLATE(x) ((unsigned)(x) <= %d ? yytranslate[x] : %d)\n", + max_user_token_number, nsyms); + + if (ntokens < 127) /* play it very safe; check maximum element value. */ + fprintf(ftable, "\nstatic const char yytranslate[] = { 0"); + else + fprintf(ftable, "\nstatic const short yytranslate[] = { 0"); + + j = 10; + for (i = 1; i <= max_user_token_number; i++) + { + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + fprintf(ftable, "%6d", token_translations[i]); + } + + fprintf(ftable, "\n};\n"); + } + else + { + fprintf(ftable, "\n#define YYTRANSLATE(x) (x)\n"); + } + } + + + + void output_gram(void) + { + register int i; + register int j; + register short *sp; + + fprintf(ftable, "\nstatic const short yyprhs[] = { 0"); + + j = 10; + for (i = 1; i <= nrules; i++) + { + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + fprintf(ftable, "%6d", rrhs[i]); + } + + fprintf(ftable, "\n};\n\nstatic const short yyrhs[] = {%6d", ritem[0]); + + j = 10; + for (sp = ritem + 1; *sp; sp++) + { + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + if (*sp > 0) + fprintf(ftable, "%6d", *sp); + else + fprintf(ftable, " 0"); + } + + fprintf(ftable, "\n};\n"); + } + + + + void output_stos(void) + { + register int i; + register int j; + + fprintf(ftable, "\nstatic const short yystos[] = { 0"); + + j = 10; + for (i = 1; i < nstates; i++) + { + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + fprintf(ftable, "%6d", accessing_symbol[i]); + } + + fprintf(ftable, "\n};\n"); + } + + + + void output_rule_data(void) + { + register int i; + register int j; + + fprintf(ftable, "\nstatic const short yyrline[] = { 0"); + + j = 10; + for (i = 1; i <= nrules; i++) + { + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + fprintf(ftable, "%6d", rline[i]); + } + + /* Output the table of token names. */ + + fprintf(ftable, "\n};\n\nstatic const char * const yytname[] = { 0"); + + j = 10; + for (i = 1; i <= ntokens; i++) + { + register char *p; + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + putc ('\"', ftable); + + for (p = tags[i]; *p; p++) + if (*p == '"' || *p == '\\') + fprintf(ftable, "\\%c", *p); + else if (*p == '\n') + fprintf(ftable, "\\n"); + else if (*p == '\t') + fprintf(ftable, "\\t"); + else if (*p == '\b') + fprintf(ftable, "\\b"); + else if (*p < 040 || *p >= 0177) + fprintf(ftable, "\\%03o", *p); + else + putc(*p, ftable); + + putc ('\"', ftable); + } + + fprintf(ftable, "\n};\n\nstatic const short yyr1[] = { 0"); + + j = 10; + for (i = 1; i <= nrules; i++) + { + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + fprintf(ftable, "%6d", rlhs[i]); + } + + FREE(rlhs + 1); + + fprintf(ftable, "\n};\n\nstatic const short yyr2[] = { 0"); + + j = 10; + for (i = 1; i < nrules; i++) + { + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + fprintf(ftable, "%6d", rrhs[i + 1] - rrhs[i] - 1); + } + + putc(',', ftable); + if (j >= 10) + putc('\n', ftable); + + fprintf(ftable, "%6d\n};\n", nitems - rrhs[nrules] - 1); + FREE(rrhs + 1); + } + + + + void output_defines(void) + { + fprintf(ftable, "\n\n#define\tYYFINAL\t\t%d\n", final_state); + fprintf(ftable, "#define\tYYFLAG\t\t%d\n", MINSHORT); + fprintf(ftable, "#define\tYYNTBASE\t%d\n", ntokens); + } + + + + /* compute and output yydefact, yydefgoto, yypact, yypgoto, yytable and yycheck. */ + + void output_actions(void) + { + nvectors = nstates + nvars; + + froms = NEW2(nvectors, short *); + tos = NEW2(nvectors, short *); + tally = NEW2(nvectors, short); + width = NEW2(nvectors, short); + + token_actions(); + free_shifts(); + free_reductions(); + FREE(lookaheads); + FREE(LA); + FREE(LAruleno); + FREE(accessing_symbol); + + goto_actions(); + FREE(goto_map + ntokens); + FREE(from_state); + FREE(to_state); + + sort_actions(); + pack_table(); + output_base(); + output_table(); + output_check(); + } + + + + /* figure out the actions for the specified state, indexed by lookahead token type. + + The yydefact table is output now. The detailed info + is saved for putting into yytable later. */ + + void token_actions(void) + { + register int i; + register int j; + register int k; + + actrow = NEW2(ntokens, short); + + k = action_row(0); + fprintf(ftable, "\nstatic const short yydefact[] = {%6d", k); + save_row(0); + + j = 10; + for (i = 1; i < nstates; i++) + { + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + k = action_row(i); + fprintf(ftable, "%6d", k); + save_row(i); + } + + fprintf(ftable, "\n};\n"); + FREE(actrow); + } + + + + /* Decide what to do for each type of token if seen as the lookahead token in specified state. + The value returned is used as the default action (yydefact) for the state. + In addition, actrow is filled with what to do for each kind of token, + index by symbol number, with zero meaning do the default action. + The value MINSHORT, a very negative number, means this situation + is an error. The parser recognizes this value specially. + + This is where conflicts are resolved. The loop over lookahead rules + considered lower-numbered rules last, and the last rule considered that likes + a token gets to handle it. */ + + int action_row(int state) + { + register int i; + register int j; + register int k; + register int m; + register int n; + register int count; + register int default_rule; + register int nreds; + register int max; + register int rule; + register int shift_state; + register int symbol; + register unsigned mask; + register unsigned *wordp; + register reductions *redp; + register shifts *shiftp; + register errs *errp; + int nodefault = 0; /* set nonzero to inhibit having any default reduction */ + + for (i = 0; i < ntokens; i++) + actrow[i] = 0; + + default_rule = 0; + nreds = 0; + redp = reduction_table[state]; + + if (redp) + { + nreds = redp->nreds; + + if (nreds >= 1) + { + /* loop over all the rules available here which require lookahead */ + m = lookaheads[state]; + n = lookaheads[state + 1]; + + for (i = n - 1; i >= m; i--) + { + rule = - LAruleno[i]; + wordp = LA + i * tokensetsize; + mask = 1; + + /* and find each token which the rule finds acceptable to come next */ + for (j = 0; j < ntokens; j++) + { + /* and record this rule as the rule to use if that token follows. */ + if (mask & *wordp) + actrow[j] = rule; + + mask <<= 1; + if (mask == 0) + { + mask = 1; + wordp++; + } + } + } + } + } + + shiftp = shift_table[state]; + + /* now see which tokens are allowed for shifts in this state. + For them, record the shift as the thing to do. So shift is preferred to reduce. */ + + if (shiftp) + { + k = shiftp->nshifts; + + for (i = 0; i < k; i++) + { + shift_state = shiftp->shifts[i]; + if (! shift_state) continue; + + symbol = accessing_symbol[shift_state]; + + if (ISVAR(symbol)) + break; + + actrow[symbol] = shift_state; + + /* do not use any default reduction if there is a shift for error */ + + if (symbol == error_token_number) nodefault = 1; + } + } + + errp = err_table[state]; + + /* See which tokens are an explicit error in this state + (due to %nonassoc). For them, record MINSHORT as the action. */ + + if (errp) + { + k = errp->nerrs; + + for (i = 0; i < k; i++) + { + symbol = errp->errs[i]; + actrow[symbol] = MINSHORT; + } + } + + /* now find the most common reduction and make it the default action for this state. */ + + if (nreds >= 1 && ! nodefault) + { + if (consistent[state]) + default_rule = redp->rules[0]; + else + { + max = 0; + for (i = m; i < n; i++) + { + count = 0; + rule = - LAruleno[i]; + + for (j = 0; j < ntokens; j++) + { + if (actrow[j] == rule) + count++; + } + + if (count > max) + { + max = count; + default_rule = rule; + } + } + + /* actions which match the default are replaced with zero, + which means "use the default" */ + + if (max > 0) + { + for (j = 0; j < ntokens; j++) + { + if (actrow[j] == default_rule) + actrow[j] = 0; + } + + default_rule = - default_rule; + } + } + } + + /* If have no default rule, the default is an error. + So replace any action which says "error" with "use default". */ + + if (default_rule == 0) + for (j = 0; j < ntokens; j++) + { + if (actrow[j] == MINSHORT) + actrow[j] = 0; + } + + return (default_rule); + } + + void save_row(int state) + { + register int i; + register int count; + register short *sp; + register short *sp1; + register short *sp2; + + count = 0; + for (i = 0; i < ntokens; i++) + { + if (actrow[i] != 0) + count++; + } + + if (count == 0) + return; + + froms[state] = sp1 = sp = NEW2(count, short); + tos[state] = sp2 = NEW2(count, short); + + for (i = 0; i < ntokens; i++) + { + if (actrow[i] != 0) + { + *sp1++ = i; + *sp2++ = actrow[i]; + } + } + + tally[state] = count; + width[state] = sp1[-1] - sp[0] + 1; + } + + /* figure out what to do after reducing with each rule, + depending on the saved state from before the beginning + of parsing the data that matched this rule. + + The yydefgoto table is output now. The detailed info + is saved for putting into yytable later. */ + + void goto_actions(void) + { + register int i; + register int j; + register int k; + + state_count = NEW2(nstates, short); + + k = default_goto(ntokens); + fprintf(ftable, "\nstatic const short yydefgoto[] = {%6d", k); + save_column(ntokens, k); + + j = 10; + for (i = ntokens + 1; i < nsyms; i++) + { + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + k = default_goto(i); + fprintf(ftable, "%6d", k); + save_column(i, k); + } + + fprintf(ftable, "\n};\n"); + FREE(state_count); + } + + int default_goto(int symbol) + { + register int i; + register int m; + register int n; + register int default_state; + register int max; + + m = goto_map[symbol]; + n = goto_map[symbol + 1]; + + if (m == n) + return (-1); + + for (i = 0; i < nstates; i++) + state_count[i] = 0; + + for (i = m; i < n; i++) + state_count[to_state[i]]++; + + max = 0; + default_state = -1; + + for (i = 0; i < nstates; i++) + { + if (state_count[i] > max) + { + max = state_count[i]; + default_state = i; + } + } + + return (default_state); + } + + void save_column(int symbol,int default_state) + { + register int i; + register int m; + register int n; + register short *sp; + register short *sp1; + register short *sp2; + register int count; + register int symno; + + m = goto_map[symbol]; + n = goto_map[symbol + 1]; + + count = 0; + for (i = m; i < n; i++) + { + if (to_state[i] != default_state) + count++; + } + + if (count == 0) + return; + + symno = symbol - ntokens + nstates; + + froms[symno] = sp1 = sp = NEW2(count, short); + tos[symno] = sp2 = NEW2(count, short); + + for (i = m; i < n; i++) + { + if (to_state[i] != default_state) + { + *sp1++ = from_state[i]; + *sp2++ = to_state[i]; + } + } + + tally[symno] = count; + width[symno] = sp1[-1] - sp[0] + 1; + } + + + + /* the next few functions decide how to pack + the actions and gotos information into yytable. */ + + void sort_actions(void) + { + register int i; + register int j; + register int k; + register int t; + register int w; + + order = NEW2(nvectors, short); + nentries = 0; + + for (i = 0; i < nvectors; i++) + { + if (tally[i] > 0) + { + t = tally[i]; + w = width[i]; + j = nentries - 1; + + while (j >= 0 && (width[order[j]] < w)) + j--; + + while (j >= 0 && (width[order[j]] == w) && (tally[order[j]] < t)) + j--; + + for (k = nentries - 1; k > j; k--) + order[k + 1] = order[k]; + + order[j + 1] = i; + nentries++; + } + } + } + + + + void pack_table(void) + { + register int i; + register int place; + register int state; + + base = NEW2(nvectors, short); + pos = NEW2(nentries, short); + table = NEW2(MAXTABLE, short); + check = NEW2(MAXTABLE, short); + + lowzero = 0; + high = 0; + + for (i = 0; i < nvectors; i++) + base[i] = MINSHORT; + + for (i = 0; i < MAXTABLE; i++) + check[i] = -1; + + for (i = 0; i < nentries; i++) + { + state = matching_state(i); + + if (state < 0) + place = pack_vector(i); + else + place = base[state]; + + pos[i] = place; + base[order[i]] = place; + } + + for (i = 0; i < nvectors; i++) + { + FREE(froms[i]); + FREE(tos[i]); + } + + FREE(froms); + FREE(tos); + FREE(pos); + } + + + + int matching_state(int vector) + { + register int i; + register int j; + register int k; + register int t; + register int w; + register int match; + register int prev; + + i = order[vector]; + if (i >= nstates) + return (-1); + + t = tally[i]; + w = width[i]; + + for (prev = vector - 1; prev >= 0; prev--) + { + j = order[prev]; + if (width[j] != w || tally[j] != t) + return (-1); + + match = 1; + for (k = 0; match && k < t; k++) + { + if (tos[j][k] != tos[i][k] || froms[j][k] != froms[i][k]) + match = 0; + } + + if (match) + return (j); + } + + return (-1); + } + + + + int pack_vector(int vector) + { + register int i; + register int j; + register int k; + register int t; + register int loc; + register int ok; + register short *from; + register short *to; + + i = order[vector]; + t = tally[i]; + + if (t == 0) + berror("pack_vector"); + + from = froms[i]; + to = tos[i]; + + for (j = lowzero - from[0]; j < MAXTABLE; j++) + { + ok = 1; + + for (k = 0; ok && k < t; k++) + { + loc = j + from[k]; + if (loc > MAXTABLE) + fatals("maximum table size (%d) exceeded",MAXTABLE,0,0,0,0,0,0,0); + + if (table[loc] != 0) + ok = 0; + } + + for (k = 0; ok && k < vector; k++) + { + if (pos[k] == j) + ok = 0; + } + + if (ok) + { + for (k = 0; k < t; k++) + { + loc = j + from[k]; + table[loc] = to[k]; + check[loc] = from[k]; + } + + while (table[lowzero] != 0) + lowzero++; + + if (loc > high) + high = loc; + + return (j); + } + } + + berror("pack_vector"); + return 0; /* JF keep lint happy */ + } + + + + /* the following functions output yytable, yycheck + and the vectors whose elements index the portion starts */ + + void output_base(void) + { + register int i; + register int j; + + fprintf(ftable, "\nstatic const short yypact[] = {%6d", base[0]); + + j = 10; + for (i = 1; i < nstates; i++) + { + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + fprintf(ftable, "%6d", base[i]); + } + + fprintf(ftable, "\n};\n\nstatic const short yypgoto[] = {%6d", base[nstates]); + + j = 10; + for (i = nstates + 1; i < nvectors; i++) + { + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + fprintf(ftable, "%6d", base[i]); + } + + fprintf(ftable, "\n};\n"); + FREE(base); + } + + void output_table(void) + { + register int i; + register int j; + + fprintf(ftable, "\n\n#define\tYYLAST\t\t%d\n\n", high); + fprintf(ftable, "\nstatic const short yytable[] = {%6d", table[0]); + + j = 10; + for (i = 1; i <= high; i++) + { + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + fprintf(ftable, "%6d", table[i]); + } + + fprintf(ftable, "\n};\n"); + FREE(table); + } + + void output_check(void) + { + register int i; + register int j; + + fprintf(ftable, "\nstatic const short yycheck[] = {%6d", check[0]); + + j = 10; + for (i = 1; i <= high; i++) + { + putc(',', ftable); + + if (j >= 10) + { + putc('\n', ftable); + j = 1; + } + else + { + j++; + } + + fprintf(ftable, "%6d", check[i]); + } + + fprintf(ftable, "\n};\n"); + FREE(check); + } + + + + /* copy the parser code into the ftable file at the end. */ + + void output_parser(void) + { + register int c; + #ifdef DONTDEF + FILE *fpars; + #else + #define fpars fparser + #endif + + if (pure_parser) + fprintf(ftable, "#define YYIMPURE 1\n\n"); + else + fprintf(ftable, "#define YYPURE 1\n\n"); + + #ifdef DONTDEF /* JF no longer needed 'cuz open_extra_files changes the + currently open parser from bison.simple to bison.hairy */ + if (semantic_parser) + fpars = fparser; + else fpars = fparser1; + #endif + + c = getc(fpars); + while (c != EOF) + { + /* This is a kludgy but easy-to-write way to delete lines + that start with `#line'. */ + if (nolinesflag) + if (c == '\n') + { + putc (c, ftable); + c = getc (fpars); + if (c == '#') + { + c = getc (fpars); + if (c == 'l') + { + c = getc (fpars); + if (c == 'i') + { + c = getc (fpars); + if (c == 'n') + { + c = getc (fpars); + if (c == 'e') + { + while (1) + { + c = getc (fpars); + if (c == '\n' || c < 0) + break; + } + c = getc (fpars); + } + else + fprintf (ftable, "#lin"); + } + else + fprintf (ftable, "#li"); + } + else + fprintf (ftable, "#l"); + } + else + fprintf (ftable, "#"); + } + } + + if (c == '$') { + #ifdef DONTDEF + fprintf(ftable, "#include \"%s\"\n", actfile); + #else + /* JF don't #include the action file. Stuff it right in. */ + rewind(faction); + for(c=getc(faction);c!=EOF;c=getc(faction)) + putc(c,ftable); + #endif + } else + putc(c, ftable); + c = getc(fpars); + } + } + + + + void output_program(void) + { + register int c; + extern int lineno; + + fprintf(ftable, "#line %d \"%s\"\n", lineno, infile); + + c = getc(finput); + while (c != EOF) + { + putc(c, ftable); + c = getc(finput); + } + } + + + + void free_itemsets(void) + { + register core *cp,*cptmp; + + FREE(state_table); + + for (cp = first_state; cp; cp = cptmp) { + cptmp=cp->next; + FREE(cp); + } + } + + void free_shifts(void) + { + register shifts *sp,*sptmp;/* JF derefrenced freed ptr */ + + FREE(shift_table); + + for (sp = first_shift; sp; sp = sptmp) { + sptmp=sp->next; + FREE(sp); + } + } + + void free_reductions(void) + { + register reductions *rp,*rptmp;/* JF fixed freed ptr */ + + FREE(reduction_table); + + for (rp = first_reduction; rp; rp = rptmp) { + rptmp=rp->next; + FREE(rp); + } + } + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/parse.y.in diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/parse.y.in:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/parse.y.in Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,763 ---- + %{ + #include + #include + #include "attr.h" + int yylex(); + void yyerror(char* s); + #include "symtab.h" + /* Global variables */ + scopeEntry current = NULL; /* Points to current scope */ + scopeEntry temp = NULL; /* Used temporarily for adding and/or + removing scopes */ + %} + + %union { int number; + tokentype token; + BaseType basetype; + typeinfo totaltype; + namelist names; + expnode exps; + explist elist;} + + %token PROG PERIOD PROC FUNC VAR ARRAY RANGE OF + %token INT CHAR BOOL WRITELN THEN ELSE IF DO WHILE + %token BEG END ASG NOT TRUE_TOK FALSE_TOK + %token ID CCONST ICONST + + %type stype + %type type exp constant lhs var + %type idlist vardcl vardcls parmlist parms parm variables + %type explist optexplist + + %start program + %nonassoc '=' NEQ LT LEQ GEQ GT + %left '+' '-' OR + %left '*' AND DIV + %right NOT + + %% + program : PROG ID + { enterblock(); } + ';' block PERIOD + {leaveblock();}; + + block : variables + { + /* Seen all the variables so declare them in the current scope */ + symTabEntry s; + namenode tmpnode; + + tmpnode = $1.firstname; + while ( tmpnode != NULL ) + { + if ( lookup( tmpnode -> name , current ) == NULL ) + { + s = declare(tmpnode -> name,tmpnode -> idtype.basetype, + tmpnode -> idtype.gentype,tmpnode -> ptype, + tmpnode -> idtype.number, tmpnode -> idtype.endnum); + } + else + printf("\n***Error: duplicate declaration of %s\n", tmpnode -> + name); + tmpnode = tmpnode -> next; + } + } + procdcls cmpdstmt; + + procdcls : procdcls procdcl | /* empty */ ; + + procdcl : PROC ID + { + symTabEntry find; + + if (lookup($2.str,current) == NULL) + find = declare($2.str,VOIDTYPE,PROCTYPE,NOTPARM,-1,-1); + /* Just make a spot in the outerscope to hold the name of the */ + /* procedure */ + else + printf("\n***Error: duplicate declaration of %s\n",$2.str); + enterblock(); + procentry($2.str,PROCTYPE); + } + parmlist + { /* After we have seen the parmlist, install it and */ + int n; /* update the number field */ + + n = installparms($4); + current -> procedure -> number = n; + } + ';' block ';' + { + symTabEntry find; + + find = lookup($2.str, current -> outerscope); /* Before we leave the block */ + if ( find != NULL ) /* We must transfer the link */ + { /* to the outer scope */ + find -> number = current -> procedure -> number; + find -> formals = current -> procedure -> formals; + } + leaveblock(); + } + | FUNC ID + { /* Same as above up until where 'stype' is */ + symTabEntry find; + if (lookup($2.str,current) == NULL) + find = declare($2.str,VOIDTYPE,FUNCTYPE,NOTPARM,-1,-1); + else + printf("\n***Error: duplicate declaration of %s\n",$2.str); + enterblock(); + procentry($2.str,FUNCTYPE); + } + parmlist + { + int n; + + n = installparms($4); + current -> procedure -> number = n; + } + ':' stype ';' + { finishfunc($7); + /* We NOW know what type it returns so record it */} + block ';' + { + symTabEntry find; + + find = lookup($2.str, current -> outerscope ); + if ( find != NULL ) + { /* Before we leave the block, we must make the link in the outer scope */ + find -> number = current -> procedure -> number; + find -> basetype = current -> procedure -> basetype; + find -> formals = current -> procedure -> formals; + } + leaveblock(); + } + ; + parmlist : '(' parms ')' + { $$ = $2; } /* Pass up the list of params */ + | /* empty */ + { $$.firstname = NULL; /* There are no params so the list is NULL */ + $$.lastname = NULL; }; + + parms : parms ';' parm + { /* Link the current list to the new parmlist and send it up */ + $1.lastname -> next = $3.firstname; + $$.firstname = $1.firstname; + $$.lastname = $3.lastname; + } + | parm + { $$ = $1; }; /* Send up the base case */ + + parm : VAR vardcl + { /* We know that these are pass by reference so record + it in all the nodes */ + namenode tmpnode; + + tmpnode = $2.firstname; + while ( tmpnode != NULL ) + { + tmpnode -> ptype = REFPARM; + tmpnode = tmpnode -> next; + } + $$ = $2; /* Send up the new list */ + } + | vardcl + { /* We know that these are pass by value so record + it in all the nodes */ + namenode tmpnode; + + tmpnode = $1.firstname; + while ( tmpnode != NULL ) + { + tmpnode -> ptype = VALPARM; + tmpnode = tmpnode -> next; + } + $$ = $1; /* Send up the new list */ + }; + + variables: /* empty */ + { $$.firstname = NULL; /* No variables = no list */ + $$.lastname = NULL; } + | VAR vardcls /* Pass up the list of variables */ + { $$ = $2; }; + + vardcls : vardcls vardcl ';' + { /* Concatenates the 2 namelists */ + $1.lastname -> next = $2.firstname; + $$.firstname = $1.firstname; + $$.lastname = $2.lastname; + } + | vardcl ';' + { $$ = $1; }; + vardcl : idlist ':' type + { /* We have a list of IDs and we have their type so + we can now record them to be all of the same type */ + namenode tmpnode; + + tmpnode = $1.firstname; + while ( tmpnode != NULL ) + { + tmpnode->idtype.basetype = $3.basetype; + tmpnode->idtype.gentype = $3.gentype; + tmpnode->idtype.number = $3.number; + tmpnode->idtype.endnum = $3.endnum; + tmpnode->ptype = NOTPARM; + tmpnode = tmpnode -> next; + } + $$ = $1; /* Send up the new list */ + }; + idlist : idlist ',' ID + { /* Hook the new ID to the current list of IDs */ + namenode tmpname1 = NULL; + + tmpname1 = (namenode) malloc(sizeof(struct _namenode)); + tmpname1 -> name = $3.str; + tmpname1 -> next = NULL; + $1.lastname -> next = tmpname1; + $$.firstname = $1.firstname; + $$.lastname = tmpname1; + } + | ID + { /* Start the linked list with the first ID */ + namenode tmpname1 = NULL; + + tmpname1 = (namenode) malloc(sizeof(struct _namenode)); + tmpname1 -> name = $1.str; + tmpname1 -> next = NULL; + $$.firstname = tmpname1; + $$.lastname = tmpname1; + } + ; + type : ARRAY '[' ICONST RANGE ICONST ']' OF stype + { if ($3.num > $5.num) + { + printf("\n***Error: lower bound exceeds upper bound\n"); + $$.basetype = $8; /* Basetype is whatever 'stype' was */ + $$.gentype = ARRAYTYPE; + $$.number = $5.num; + $$.endnum = $3.num; + } + else + { + $$.basetype = $8; /* Basetype is whatever 'stype' was */ + $$.gentype = ARRAYTYPE; + $$.number = $3.num; + $$.endnum = $5.num; + } + } + | stype + { + $$.basetype = $1; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + }; + + stype : INT { $$ = INTTYPE; /* Send up the basetypes */ } + | CHAR { $$ = CHARTYPE; } + | BOOL { $$ = BOOLTYPE; }; + + stmtlist : stmtlist ';' stmt { } + | stmt { }; + + stmt : ifstmt { } + | wstmt { } + | astmt { } + | procstmt { } + | cmpdstmt { } + | writestmt { }; + + writestmt: WRITELN '(' exp ')' + { if (( $3.basetype == INTTYPE ) || ( $3.basetype == STRINGTYPE )) + { /* Must be a string or int */ + if ( $3.gentype != NOTYPE ) + printf("\n***Error: illegal type for writeln\n"); /* No arrays or such */ + } + else + printf("\n***Error: illegal type for writeln\n"); /* Only ints and strings */ + }; + + procstmt: ID optexplist + { + symTabEntry s; + + s = lookupALL($1.str); + if ( s == NULL ) /* ID not found */ + printf("\n***Error: undeclared identifier %s\n",$1.str); + else + { + if ( s -> gentype != PROCTYPE ) /* Found, but not a procedure */ + printf("\n***Error: id %s is not a procedure\n",$1.str); + else + { /* Found and it is a procedure so check the parameters */ + int check; + check = checkparams( s -> formals , $2 ); + } + } + } + ; + ifstmt : ifhead THEN stmt ELSE stmt + | ifhead THEN stmt + ; + ifhead : IF exp + { /* only booleans */ + if ($2.basetype != BOOLTYPE) + printf("\n***Error: exp in if stmt must be boolean\n"); + } + ; + wstmt : whead DO stmt + ; + whead : WHILE exp + { /* only booleans */ + if ($2.basetype != BOOLTYPE) + printf("\n***Error: exp in while stmt must be boolean\n"); + }; + + cmpdstmt: BEG stmtlist END; + + astmt : lhs exp + { /* Make sure the assignment types match */ + if (!(match($1,$2))) + printf("\n***Error: assignment types do not match\n"); + }; + + lhs : var ASG + { $$ = $1; }; + + optexplist: /* empty */ + { $$.firstexp = NULL; /* No optexplist = NULL list */ + $$.lastexp = NULL; } + | '(' explist ')' + { $$ = $2; }; + + explist : explist ',' exp + { /* Hook the new expression type to the current list */ + expnode tmpnode; + + tmpnode = makeexp($3); + $1.lastexp -> next = tmpnode; + $$.firstexp = $1.firstexp; + $$.lastexp = tmpnode; + } + | exp + { /* Start the list with the first expression */ + expnode tmpnode; + + tmpnode = makeexp($1); + $$.firstexp = tmpnode; + $$.lastexp = tmpnode; + }; + + exp : exp '+' exp + { /* '+' requires integers */ + + if (( $1.basetype != INTTYPE ) || ( $3.basetype != INTTYPE ) || + ( $1.gentype != NOTYPE ) || ( $3.gentype != NOTYPE )) + printf("\n***Error: operands of '+' must be integers\n"); + $$.basetype = INTTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | exp '-' exp + { /* '-' requires integers */ + + if (( $1.basetype != INTTYPE ) || ( $3.basetype != INTTYPE ) || + ( $1.gentype != NOTYPE ) || ( $3.gentype != NOTYPE )) + printf("\n***Error: operands of '-' must be integers\n"); + $$.basetype = INTTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | '-' exp %prec NOT + { /* unary '-' requires an integer */ + + if (( $2.basetype != INTTYPE ) || ( $2.gentype != NOTYPE )) + printf("\n***Error: right operand of '-' must be an integer\n"); + $$.basetype = INTTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | exp '*' exp + { /* '*' requires integers */ + + if (( $1.basetype != INTTYPE ) || ( $3.basetype != INTTYPE ) || + ( $1.gentype != NOTYPE ) || ( $3.gentype != NOTYPE )) + printf("\n***Error: operands of '*' must be integers\n"); + $$.basetype = INTTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | exp DIV exp + { /* DIV requires integers */ + + if (( $1.basetype != INTTYPE ) || ( $3.basetype != INTTYPE ) || + ( $1.gentype != NOTYPE ) || ( $3.gentype != NOTYPE )) + printf("\n***Error: operands of div must be integers\n"); + $$.basetype = INTTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | exp NEQ exp + { /* '<>' requires the same types AND only base types */ + + if ( $1.basetype != $3.basetype ) + printf("\n***Error: operands of '<>' have different types\n"); + if (( $1.gentype != NOTYPE ) || ( $3.gentype != NOTYPE )) + printf("\n***Error: operands of '<>' must be base types\n"); + $$.basetype = BOOLTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | exp '=' exp + { /* '=' requires the same types AND only base types */ + + if (($1.basetype != $3.basetype ) || ( $1.gentype != NOTYPE ) || + ( $3.gentype != NOTYPE )) + printf("\n***Error: operands of '=' have different types\n"); + $$.basetype = BOOLTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | exp GEQ exp + { /* '>=' requires integers */ + + if (( $1.basetype != INTTYPE ) || ( $3.basetype != INTTYPE ) || + ( $1.gentype != NOTYPE ) || ( $3.gentype != NOTYPE )) + printf("\n***Error: operands of '>=' must be integers\n"); + $$.basetype = BOOLTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | exp GT exp + { /* '>' requires integers */ + + if (( $1.basetype != INTTYPE ) || ( $3.basetype != INTTYPE ) || + ( $1.gentype != NOTYPE ) || ( $3.gentype != NOTYPE )) + printf("\n***Error: operands of '>' must be integers\n"); + $$.basetype = BOOLTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | exp LT exp + { /* '<' requires integers */ + + if (( $1.basetype != INTTYPE ) || ( $3.basetype != INTTYPE ) || + ( $1.gentype != NOTYPE ) || ( $3.gentype != NOTYPE )) + printf("\n***Error: operands of '<' must be integers\n"); + $$.basetype = BOOLTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | exp LEQ exp + { /* '<=' requires integers */ + + if (( $1.basetype != INTTYPE ) || ( $3.basetype != INTTYPE ) || + ( $1.gentype != NOTYPE ) || ( $3.gentype != NOTYPE )) + printf("\n***Error: operands of '<=' must be integers\n"); + $$.basetype = BOOLTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | exp AND exp + { /* AND requires booleans */ + + if (( $1.basetype != BOOLTYPE ) || ( $3.basetype != BOOLTYPE ) || + ( $1.gentype != NOTYPE ) || ( $3.gentype != NOTYPE )) + printf("\n***Error: operands of AND must be boolean\n"); + $$.basetype = BOOLTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | exp OR exp + { /* OR requires booleans */ + + if (( $1.basetype != BOOLTYPE ) || ( $3.basetype != BOOLTYPE ) || + ( $1.gentype != NOTYPE ) || ( $3.gentype != NOTYPE )) + printf("\n***Error: operands of OR must be boolean\n"); + $$.basetype = BOOLTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | NOT exp + { /* NOT requires a boolean */ + + if (( $2.basetype != BOOLTYPE ) || ( $2.gentype != NOTYPE )) + printf("\n***Error: right operand of NOT must be boolean\n"); + $$.basetype = $2.basetype; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + | '(' exp ')' + { /* Simply pass up the type of the expression within the + parentheses */ + + $$.basetype = $2.basetype; + $$.gentype = $2.gentype; + $$.number = $2.number; + $$.endnum = $2.endnum; + } + | ID '(' explist ')' + { /* This should be a function in an expression */ + + symTabEntry s; + + s = lookupALL($1.str); + if ( s == NULL ) + { + printf("\n***Error: undeclared identifier: %s\n",$1.str); + $$.basetype = VOIDTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + else + { + if ( s -> gentype == FUNCTYPE ) /* Make sure it is a function */ + { + int check; + + check = checkparams( s -> formals , $3 ); + $$.basetype = s -> basetype; /* Take the return type */ + $$.gentype = NOTYPE; /* of the function */ + $$.number = -1; + $$.endnum = -1; + } + else + { /* Not a function : ERROR !! */ + + printf("\n***Error: id %s is not a function\n",$1.str); + $$.basetype = VOIDTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + } + } + | ID + { /* This can be a variable or a function with no parameters */ + + symTabEntry s; + + s = lookupALL($1.str); + if ( s == NULL) + { + printf("\n***Error: undeclared identifier: %s\n",$1.str); + $$.basetype = VOIDTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + else + { /* No procedures allowed in expressions */ + + if (s -> gentype == PROCTYPE ) + { + printf("\n***Error: illegal type for expression\n"); + $$.basetype = VOIDTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = 1; + } + if ( s -> gentype == ARRAYTYPE ) + { + $$.basetype = s -> basetype; + $$.gentype = ARRAYTYPE; + $$.number = s -> number; + $$.endnum = s -> endnum; + } + if ( s -> gentype == FUNCTYPE ) + { /* Can be a function ONLY if there are no formal parameters */ + + if ( s -> formals != NULL ) + printf("\n***Error: too few actual parameters\n"); + $$.basetype = s -> basetype; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + if ( s -> gentype == NOTYPE ) + { + $$.basetype = s -> basetype; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + } + } + | ID '[' exp ']' + { /* This should be an array only */ + + symTabEntry s; + + s = lookupALL($1.str); + if ( s == NULL) + { + printf("\n***Error: undeclared identifier: %s\n",$1.str); + $$.basetype = VOIDTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + else + { /* Check variable AND the subscript */ + + if ( s -> gentype != ARRAYTYPE ) + printf("\n***Error: id %s is not an array\n",$1.str); + if (( $3.basetype != INTTYPE ) || ( $3.gentype != NOTYPE )) + printf("\n***Error: subscript exp not type integer\n"); + $$.basetype = s -> basetype; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + } + | constant { $$ = $1; /* Simply send up the constant's type */ }; + + var : ID + { /* Left hand side without '[' and ']' can ONLY be a variable OR + the function from the CURRENT scope */ + + symTabEntry s; + + s = lookupALL($1.str); + if ( s == NULL) + { + printf("\n***Error: undeclared identifier: %s\n",$1.str); + $$.basetype = VOIDTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + else + { /* Function can only be on the left side if it is + defining the current function */ + + if ( s -> gentype == FUNCTYPE ) + { + if ( s == current -> procedure ) + { + $$.basetype = s -> basetype; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + else + { /* Otherwise, it is an error */ + + printf("\n***Error: function name on left side of :=\n"); + $$.basetype = VOIDTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.number = -1; + } + } + else + { + if ( s -> gentype == NOTYPE ) + { + $$.basetype = s -> basetype; + $$.gentype = NOTYPE; + $$.number = s -> number; + $$.endnum = s -> endnum; + } + else + { /* No arrays or procedures on the left side */ + + printf("\n***Error: assignment to nonscalar\n"); + $$.basetype = VOIDTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + } + } + } + | ID '[' exp ']' + { /* This should be an array AND an index */ + + symTabEntry s; + + s = lookupALL($1.str); + if ( s == NULL ) + { + printf("\n***Error: undeclared identifier: %s\n",$1.str); + $$.basetype = VOIDTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + else + { /* Check to make sure it IS an array and the index is + an integer */ + + if ( s -> gentype == ARRAYTYPE ) + { + if (( $3.basetype != INTTYPE ) || ( $3.gentype != NOTYPE )) + printf("\n***Error: subscript exp is not type integer\n"); + $$.basetype = s -> basetype; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + else + { /* This is not an array */ + printf("\n***Error: id %s is not an array\n",$1.str); + $$.basetype = VOIDTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; + } + } + }; + + constant: ICONST + { $$.basetype = INTTYPE; /* Basic integer */ + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; } + | CCONST + { + if ( strlen($1.str) == 3 ) /* Single character */ + $$.basetype = CHARTYPE; + else + $$.basetype = STRINGTYPE; /* String */ + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; } + | TRUE_TOK + { $$.basetype = BOOLTYPE; /* TRUE and FALSE are both booleans */ + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; } + | FALSE_TOK + { $$.basetype = BOOLTYPE; + $$.gentype = NOTYPE; + $$.number = -1; + $$.endnum = -1; }; + + %% + + void + yyerror(char* s) { + fprintf(stderr,"%s\n",s); + } + + int + main() { + printf("1\t"); + yyparse(); + return 1; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/print.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/print.c:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/print.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,226 ---- + /* Print information on generated parser, for bison, + Copyright (C) 1984, 1986 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + #include + #include "machine.h" + #include "new.h" + #include "files.h" + #include "gram.h" + #include "state.h" + + + extern char **tags; + extern int nstates; + extern short *accessing_symbol; + extern core **state_table; + extern shifts **shift_table; + extern errs **err_table; + extern reductions **reduction_table; + extern char *consistent; + extern char any_conflicts; + extern char *conflicts; + + extern void conflict_log(void); + extern void verbose_conflict_log(void); + extern void print_reductions(int state); + + void print_token(int extnum,int token); + void print_state(int state); + void print_core(int state); + void print_actions(int state); + + void terse(void) + { + if (any_conflicts) + { + conflict_log(); + } + } + + void verbose(void) + { + register int i; + + if (any_conflicts) + verbose_conflict_log(); + + fprintf(foutput, "\n\ntoken types:\n"); + print_token (-1, 0); + if (translations) + { + for (i = 0; i <= max_user_token_number; i++) + /* Don't mention all the meaningless ones. */ + if (token_translations[i] != 2) + print_token (i, token_translations[i]); + } + else + for (i = 1; i < ntokens; i++) + print_token (i, i); + + for (i = 0; i < nstates; i++) + { + print_state(i); + } + } + + void print_token(int extnum,int token) + { + fprintf(foutput, " type %d is %s\n", extnum, tags[token]); + } + + void print_state(int state) + { + fprintf(foutput, "\n\nstate %d\n\n", state); + print_core(state); + print_actions(state); + } + + void print_core(int state) + { + register int i; + register int k; + register int rule; + register core *statep; + register short *sp; + register short *sp1; + + statep = state_table[state]; + k = statep->nitems; + + if (k == 0) return; + + for (i = 0; i < k; i++) + { + sp1 = sp = ritem + statep->items[i]; + + while (*sp > 0) + sp++; + + rule = -(*sp); + fprintf(foutput, " %s -> ", tags[rlhs[rule]]); + + for (sp = ritem + rrhs[rule]; sp < sp1; sp++) + { + fprintf(foutput, "%s ", tags[*sp]); + } + + putc('.', foutput); + + while (*sp > 0) + { + fprintf(foutput, " %s", tags[*sp]); + sp++; + } + + fprintf (foutput, " (%d)", rule); + putc('\n', foutput); + } + + putc('\n', foutput); + } + + void print_actions(int state) + { + register int i; + register int k; + register int state1; + register int symbol; + register shifts *shiftp; + register errs *errp; + register reductions *redp; + register int rule; + + shiftp = shift_table[state]; + redp = reduction_table[state]; + errp = err_table[state]; + + if (!shiftp && !redp) + { + fprintf(foutput, " NO ACTIONS\n"); + return; + } + + if (shiftp) + { + k = shiftp->nshifts; + + for (i = 0; i < k; i++) + { + if (! shiftp->shifts[i]) continue; + state1 = shiftp->shifts[i]; + symbol = accessing_symbol[state1]; + /* if (ISVAR(symbol)) break; */ + fprintf(foutput, " %-4s\tshift %d\n", tags[symbol], state1); + } + + if (i > 0) + putc('\n', foutput); + } + else + { + i = 0; + k = 0; + } + + if (errp) + { + k = errp->nerrs; + + for (i = 0; i < k; i++) + { + if (! errp->errs[i]) continue; + symbol = errp->errs[i]; + fprintf(foutput, " %-4s\terror (nonassociative)\n", tags[symbol]); + } + + if (i > 0) + putc('\n', foutput); + } + else + { + i = 0; + k = 0; + } + + if (consistent[state] && redp) + { + rule = redp->rules[0]; + symbol = rlhs[rule]; + fprintf(foutput, " $default\treduce %d (%s)\n\n", + rule, tags[symbol]); + } + else if (redp) + { + print_reductions(state); + } + + if (i < k) + { + for (; i < k; i++) + { + if (! shiftp->shifts[i]) continue; + state1 = shiftp->shifts[i]; + symbol = accessing_symbol[state1]; + fprintf(foutput, " %-4s\tgoto %d\n", tags[symbol], state1); + } + + putc('\n', foutput); + } + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/reader.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/reader.c:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/reader.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,1738 ---- + /* Input parser for bison + Copyright (C) 1984, 1986 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* read in the grammar specification and record it in the format described in gram.h. + All guards are copied into the fguard file and all actions into faction, + in each case forming the body of a C function (yyguard or yyaction) + which contains a switch statement to decide which guard or action to execute. + + The entry point is reader(). */ + + #include + #include + #include "files.h" + #include "new.h" + #include "symtab.h" + #include "lex.h" + #include "gram.h" + + + #define LTYPESTR "\n#ifndef YYLTYPE\ntypedef\n struct yyltype\n\ + {\n int first_line;\n int first_column;\n\ + int last_line;\n int last_column;\n }\n\ + yyltype;\n\n#define YYLTYPE yyltype\n#endif\n\n" + + /* Number of slots allocated (but not necessarily used yet) in `rline' */ + int rline_allocated; + + extern int definesflag; + extern int nolinesflag; + extern bucket *symval; + extern int numval; + extern int failure; + extern int expected_conflicts; + + typedef + struct symbol_list + { + struct symbol_list *next; + bucket *sym; + bucket *ruleprec; + } + symbol_list; + + + + int lineno; + symbol_list *grammar; + int start_flag; + bucket *startval; + char **tags; + + static int typed; /* nonzero if %union has been seen. */ + + static int lastprec; /* incremented for each %left, %right or %nonassoc seen */ + + static int gensym_count; /* incremented for each generated symbol */ + + static bucket *errtoken; + + /* Nonzero if any action or guard uses the @n construct. */ + static int yylsp_needed; + + extern void init_lex(void); + extern void tabinit(void); + extern void output_headers(void); + extern void output_trailers(void); + extern void free_symtab(void); + extern int skip_white_space(void); + extern int parse_percent_token(void); + extern void open_extra_files(void); + extern void fatal(char *s); + extern void fatals(char *fmt,int x1,int x2,int x3,int x4,int x5,int x6, + int x7,int x8); + extern int lex(void); + extern void done(int k); + + void read_declarations(void); + void output_ltype(void); + void readgram(void); + void packsymbols(void); + void packgram(void); + void copy_definition(void); + void parse_token_decl(int what_is,int what_is_not); + void parse_type_decl(void); + void parse_start_decl(void); + void parse_union_decl(void); + void parse_expect_decl(void); + void parse_assoc_decl(int assoc); + int read_signed_integer(FILE *stream); + void copy_action(symbol_list *rule,int stack_offset); + void unlex(int token); + int get_type(void); + void record_rule_line(void); + void output_token_defines(FILE *file); + + void reader(void) + { + + start_flag = 0; + startval = NULL; /* start symbol not specified yet. */ + + translations = 0; /* initially assume token number translation not needed. */ + + nsyms = 1; + nvars = 0; + nrules = 0; + nitems = 0; + rline_allocated = 10; + rline = NEW2(rline_allocated, short); + + typed = 0; + lastprec = 0; + + gensym_count = 0; + + semantic_parser = 0; + pure_parser = 0; + yylsp_needed = 0; + + grammar = NULL; + + init_lex(); + lineno = 1; + + /* initialize the symbol table. */ + tabinit(); + /* construct the error token */ + errtoken = getsym("error"); + errtoken->class = STOKEN; + /* construct a token that represents all undefined literal tokens. */ + /* it is always token number 2. */ + getsym("$illegal.")->class = STOKEN; + /* Read the declaration section. Copy %{ ... %} groups to ftable and fdefines file. + Also notice any %token, %left, etc. found there. */ + fprintf(ftable, "\n/* A Bison parser, made from %s */\n\n", infile); + read_declarations(); + /* output the definition of YYLTYPE into the fattrs and fdefines files. */ + output_ltype(); + /* start writing the guard and action files, if they are needed. */ + output_headers(); + /* read in the grammar, build grammar in list form. write out guards and actions. */ + readgram(); + /* write closing delimiters for actions and guards. */ + output_trailers(); + if (yylsp_needed) + fprintf(ftable, "#define YYLSP_NEEDED\n\n"); + /* assign the symbols their symbol numbers. + Write #defines for the token symbols into fdefines if requested. */ + packsymbols(); + /* convert the grammar into the format described in gram.h. */ + packgram(); + /* free the symbol table data structure + since symbols are now all referred to by symbol number. */ + free_symtab(); + } + + + + /* read from finput until %% is seen. Discard the %%. + Handle any % declarations, + and copy the contents of any %{ ... %} groups to fattrs. */ + + void read_declarations(void) + { + register int c; + register int tok; + + for (;;) + { + c = skip_white_space(); + + if (c == '%') + { + tok = parse_percent_token(); + + switch (tok) + { + case TWO_PERCENTS: + return; + + case PERCENT_LEFT_CURLY: + copy_definition(); + break; + + case TOKEN: + parse_token_decl (STOKEN, SNTERM); + break; + + case NTERM: + parse_token_decl (SNTERM, STOKEN); + break; + + case TYPE: + parse_type_decl(); + break; + + case START: + parse_start_decl(); + break; + + case UNION: + parse_union_decl(); + break; + + case EXPECT: + parse_expect_decl(); + break; + + case LEFT: + parse_assoc_decl(LEFT_ASSOC); + break; + + case RIGHT: + parse_assoc_decl(RIGHT_ASSOC); + break; + + case NONASSOC: + parse_assoc_decl(NON_ASSOC); + break; + + case SEMANTIC_PARSER: + semantic_parser = 1; + open_extra_files(); + break; + + case PURE_PARSER: + pure_parser = 1; + break; + + default: + fatal("junk after % in definition section"); + } + } + else if (c == EOF) + fatal("no input grammar"); + else/* JF changed msg */ + fatals("Unrecognized char '%c' in declaration section",c,0,0,0,0,0, + 0,0); + + } + } + + + /* copy the contents of a %{ ... %} into the definitions file. + The %{ has already been read. Return after reading the %}. */ + void copy_definition(void) + { + register int c; + register int match; + register int ended; + register int after_percent; /* -1 while reading a character if prev char was % */ + + if (!nolinesflag) + fprintf(fattrs, "#line %d \"%s\"\n", lineno, infile); + + after_percent = 0; + + c = getc(finput); + + for (;;) + { + switch (c) + { + case '\n': + putc(c, fattrs); + lineno++; + break; + + case '%': + after_percent = -1; + break; + + case '\'': + case '"': + match = c; + putc(c, fattrs); + c = getc(finput); + + while (c != match) + { + if (c == EOF || c == '\n') + fatal("unterminated string"); + + putc(c, fattrs); + + if (c == '\\') + { + c = getc(finput); + if (c == EOF || c == '\n') + fatal("unterminated string"); + putc(c, fattrs); + if (c == '\n') + lineno++; + } + + c = getc(finput); + } + + putc(c, fattrs); + break; + + case '/': + putc(c, fattrs); + c = getc(finput); + if (c != '*') + continue; + + putc(c, fattrs); + c = getc(finput); + + ended = 0; + while (!ended) + { + if (c == '*') + { + while (c == '*') + { + putc(c, fattrs); + c = getc(finput); + } + + if (c == '/') + { + putc(c, fattrs); + ended = 1; + } + } + else if (c == '\n') + { + lineno++; + putc(c, fattrs); + c = getc(finput); + } + else if (c == EOF) + fatal("unterminated comment in %{ definition"); + else + { + putc(c, fattrs); + c = getc(finput); + } + } + + break; + + case EOF: + fatal("unterminated %{ definition"); + + default: + putc(c, fattrs); + } + + c = getc(finput); + + if (after_percent) + { + if (c == '}') + return; + putc('%', fattrs); + } + after_percent = 0; + + } + + } + + /* parse what comes after %token or %nterm. + For %token, what_is is STOKEN and what_is_not is SNTERM. + For %nterm, the arguments are reversed. */ + + void parse_token_decl(int what_is,int what_is_not) + { + /* register int start_lineno; JF */ + register int token = 0; + register int prev; + register char *typename = 0; + int k; + extern char token_buffer[]; + + /* start_lineno = lineno; JF */ + + for (;;) + { + if(ungetc(skip_white_space(), finput) == '%') + return; + + /* if (lineno != start_lineno) + return; JF */ + + /* we have not passed a newline, so the token now starting is in this declaration */ + prev = token; + + token = lex(); + if (token == COMMA) + continue; + if (token == TYPENAME) + { + k = strlen(token_buffer); + if (typename) free (typename); + typename = NEW2(k + 1, char); + strcpy(typename, token_buffer); + } + else if (token == IDENTIFIER) + { + if (symval->class == what_is_not) + fatals("symbol %s redefined", symval->tag,0,0,0,0,0,0,0); + symval->class = what_is; + if (what_is == SNTERM) + symval->value = nvars++; + + if (typename) + { + if (symval->type_name == NULL) + symval->type_name = typename; + else + fatals("type redeclaration for %s", symval->tag,0,0,0,0,0,0,0); + } + } + else if (prev == IDENTIFIER && token == NUMBER) + { + symval->user_token_number = numval; + translations = 1; + } + else + fatal("invalid text in %token or %nterm declaration"); + } + + } + + /* parse what comes after %start */ + + void parse_start_decl(void) + { + if (start_flag) + fatal("multiple %start declarations"); + start_flag = 1; + if (lex() != IDENTIFIER) + fatal("invalid %start declaration"); + startval = symval; + } + + /* read in a %type declaration and record its information for get_type_name to access */ + + void parse_type_decl(void) + { + register int k; + register char *name; + /* register int start_lineno; JF */ + + extern char token_buffer[]; + + if (lex() != TYPENAME) + fatal("ill-formed %type declaration"); + + k = strlen(token_buffer); + name = NEW2(k + 1, char); + strcpy(name, token_buffer); + + /* start_lineno = lineno; */ + + for (;;) + { + register int t; + + if(ungetc(skip_white_space(), finput) == '%') + return; + + /* if (lineno != start_lineno) + return; JF */ + + /* we have not passed a newline, so the token now starting is in this declaration */ + + t = lex(); + + switch (t) + { + + case COMMA: + break; + + case IDENTIFIER: + if (symval->type_name == NULL) + symval->type_name = name; + else + fatals("type redeclaration for %s", symval->tag,0,0,0,0,0,0,0); + + break; + + default: + fatal("invalid %type declaration"); + } + } + } + + /* read in a %left, %right or %nonassoc declaration and record its information. */ + /* assoc is either LEFT_ASSOC, RIGHT_ASSOC or NON_ASSOC. */ + + void parse_assoc_decl(int assoc) + { + register int k; + register char *name = NULL; + /* register int start_lineno; JF */ + register int prev = 0; /* JF added = 0 to keep lint happy */ + + extern char token_buffer[]; + + lastprec++; /* assign a new precedence level. */ + + /* start_lineno = lineno; */ + + for (;;) + { + register int t; + + if(ungetc(skip_white_space(), finput) == '%') + return; + + /* if (lineno != start_lineno) + return; JF */ + + /* we have not passed a newline, so the token now starting is in this declaration */ + + t = lex(); + + switch (t) + { + + case TYPENAME: + k = strlen(token_buffer); + name = NEW2(k + 1, char); + strcpy(name, token_buffer); + break; + + case COMMA: + break; + + case IDENTIFIER: + symval->prec = lastprec; + symval->assoc = assoc; + if (symval->class == SNTERM) + fatals("symbol %s redefined", symval->tag,0,0,0,0,0,0,0); + symval->class = STOKEN; + if (name) + { /* record the type, if one is specified */ + if (symval->type_name == NULL) + symval->type_name = name; + else + fatals("type redeclaration for %s", symval->tag,0,0,0,0,0,0,0); + } + break; + + case NUMBER: + if (prev == IDENTIFIER) + { + symval->user_token_number = numval; + translations = 1; + } + else + fatal("invalid text in association declaration"); + break; + + case SEMICOLON: + return; + + default: + fatal("malformatted association declaration"); + } + + prev = t; + + } + } + + + + /* copy the union declaration into fattrs (and fdefines), + where it is made into the + definition of YYSTYPE, the type of elements of the parser value stack. */ + + void parse_union_decl(void) + { + register int c; + register int count; + register int in_comment; + + if (typed) + fatal("multiple %union declarations"); + + typed = 1; + + if (!nolinesflag) + fprintf(fattrs, "\n#line %d \"%s\"\n", lineno, infile); + else + fprintf(fattrs, "\n"); + + fprintf(fattrs, "typedef union"); + if (fdefines) + fprintf(fdefines, "typedef union"); + + count = 0; + in_comment = 0; + + c = getc(finput); + + while (c != EOF) + { + putc(c, fattrs); + if (fdefines) + putc(c, fdefines); + + switch (c) + { + case '\n': + lineno++; + break; + + case '/': + c = getc(finput); + if (c != '*') + ungetc(c, finput); + else + { + putc('*', fattrs); + if (fdefines) + putc('*', fdefines); + c = getc(finput); + in_comment = 1; + while (in_comment) + { + if (c == EOF) + fatal("unterminated comment"); + + putc(c, fattrs); + if (fdefines) + putc(c, fdefines); + if (c == '*') + { + c = getc(finput); + if (c == '/') + { + putc('/', fattrs); + if (fdefines) + putc('/', fdefines); + in_comment = 0; + } + } + else + c = getc(finput); + } + } + break; + + + case '{': + count++; + break; + + case '}': + count--; + if (count == 0) + { + fprintf(fattrs, " YYSTYPE;\n"); + if (fdefines) + fprintf(fdefines, " YYSTYPE;\n"); + /* JF don't choke on trailing semi */ + c=skip_white_space(); + if(c!=';') ungetc(c,finput); + return; + } + } + + c = getc(finput); + } + } + + /* parse the declaration %expect N which says to expect N + shift-reduce conflicts. */ + + void parse_expect_decl(void) + { + register int c; + register int count; + char buffer[20]; + + c = getc(finput); + while (c == ' ' || c == '\t') + c = getc(finput); + + count = 0; + while (c >= '0' && c <= '9') + { + if (count < 20) + buffer[count++] = c; + c = getc(finput); + } + + ungetc (c, finput); + + expected_conflicts = atoi (buffer); + } + + /* that's all of parsing the declaration section */ + + void output_ltype(void) + { + fprintf(fattrs, LTYPESTR);/* JF added YYABORT() */ + if (fdefines) + fprintf(fdefines, LTYPESTR);/* JF added YYABORT() */ + + fprintf(fattrs, "#define\tYYACCEPT\tgoto yyaccept\n"); + fprintf(fattrs, "#define\tYYABORT\tgoto yyabort\n"); + fprintf(fattrs, "#define\tYYERROR\tgoto yyerrlab\n"); + fprintf(fattrs, "#define\tyytext\t(*_yytext)\nextern char **_yytext;\n"); + fprintf(fattrs, "#define\tyylval\t(*_yylval)\nextern YYSTYPE *_yylval;\n"); + fprintf(fattrs, "#define\tyylloc\t(*_yylloc)\nextern YYLTYPE *_yylloc;\n"); + fprintf(fattrs, "#define\tyyppval\t(*_yyppval)\nextern int *_yyppval;\n"); + + if (fdefines) + { + fprintf(fdefines, "#define\tYYACCEPT\tgoto yyaccept\n"); + fprintf(fdefines, "#define\tYYABORT\tgoto yyabort\n"); + fprintf(fdefines, "#define\tYYERROR\tgoto yyerrlab\n"); + fprintf(fdefines, "#define\tyytext\t(*_yytext)\nextern char **_yytext;\n"); + fprintf(fdefines, "#define\tyylval\t(*_yylval)\nextern YYSTYPE *_yylval;\n"); + fprintf(fdefines, "#define\tyylloc\t(*_yylloc)\nextern YYLTYPE *_yylloc;\n"); + fprintf(fdefines, "#define\tyyppval\t(*_yyppval)\nextern int *_yyppval;\n"); + } + } + + + + /* Get the data type (alternative in the union) of the value for symbol n in rule rule. */ + + char *get_type_name(int n,symbol_list *rule) + { + static char *msg = "invalid $ value"; + + register int i; + register symbol_list *rp; + + if (n < 0) + fatal(msg); + + rp = rule; + i = 0; + + while (i < n) + { + rp = rp->next; + if (rp == NULL || rp->sym == NULL) + fatal(msg); + i++; + } + + return (rp->sym->type_name); + } + + + + /* after %guard is seen in the input file, + copy the actual guard into the guards file. + If the guard is followed by an action, copy that into the actions file. + stack_offset is the number of values in the current rule so far, + which says where to find $0 with respect to the top of the stack, + for the simple parser in which the stack is not popped until after the guard is run. */ + + void copy_guard(symbol_list *rule,int stack_offset) + { + register int c; + register int n; + register int count; + register int match; + register int ended; + register char *type_name; + int brace_flag = 0; + + extern char token_buffer[]; + + /* offset is always 0 if parser has already popped the stack pointer */ + if (semantic_parser) stack_offset = 0; + + fprintf(fguard, "\ncase %d:\n", nrules); + if (!nolinesflag) + fprintf(fguard, "#line %d \"%s\"\n", lineno, infile); + putc('{', fguard); + + count = 0; + c = getc(finput); + + while (brace_flag ? (count > 0) : (c != ';')) + { + switch (c) + { + case '\n': + putc(c, fguard); + lineno++; + break; + + case '{': + putc(c, fguard); + count++; + break; + + case '}': + putc(c, fguard); + brace_flag = 1; + if (count > 0) + count--; + else + fatal("unmatched right brace ('}')"); + break; + + case '\'': + case '"': + match = c; + putc(c, fguard); + c = getc(finput); + + while (c != match) + { + if (c == EOF || c == '\n') + fatal("unterminated string"); + + putc(c, fguard); + + if (c == '\\') + { + c = getc(finput); + if (c == EOF || c == '\n') + fatal("unterminated string"); + putc(c, fguard); + if (c == '\n') + lineno++; + } + + c = getc(finput); + } + + putc(c, fguard); + break; + + case '/': + putc(c, fguard); + c = getc(finput); + if (c != '*') + continue; + + putc(c, fguard); + c = getc(finput); + + ended = 0; + while (!ended) + { + if (c == '*') + { + while (c == '*') + { + putc(c, fguard); + c = getc(finput); + } + + if (c == '/') + { + putc(c, fguard); + ended = 1; + } + } + else if (c == '\n') + { + lineno++; + putc(c, fguard); + c = getc(finput); + } + else if (c == EOF) + fatal("unterminated comment"); + else + { + putc(c, fguard); + c = getc(finput); + } + } + + break; + + case '$': + c = getc(finput); + type_name = NULL; + + if (c == '<') + { + register char *cp = token_buffer; + + while ((c = getc(finput)) != '>' && c > 0) + *cp++ = c; + *cp = 0; + type_name = token_buffer; + + c = getc(finput); + } + + if (c == '$') + { + fprintf(fguard, "yyval"); + if (!type_name) type_name = rule->sym->type_name; + if (type_name) + fprintf(fguard, ".%s", type_name); + if(!type_name && typed) /* JF */ + fprintf(stderr,"%s:%d: warning: $$ of '%s' has no declared type.\n",infile,lineno,rule->sym->tag); + } + + else if (isdigit(c) || c == '-') + { + ungetc (c, finput); + n = read_signed_integer(finput); + c = getc(finput); + + if (!type_name && n > 0) + type_name = get_type_name(n, rule); + + fprintf(fguard, "yyp->yyvsp[%d]", n - stack_offset); + if (type_name) + fprintf(fguard, ".%s", type_name); + if(!type_name && typed) /* JF */ + fprintf(stderr,"%s:%d: warning: $%d of '%s' has no declared type.\n",infile,lineno,n,rule->sym->tag); + continue; + } + else + fatals("$%c is invalid",c,0,0,0,0,0,0,0); /* JF changed style */ + + break; + + case '@': + c = getc(finput); + if (isdigit(c) || c == '-') + { + ungetc (c, finput); + n = read_signed_integer(finput); + c = getc(finput); + } + else + fatals("@%c is invalid",c,0,0,0,0,0,0,0); /* JF changed style */ + + fprintf(fguard, "yyp->yylsp[%d]", n - stack_offset); + yylsp_needed = 1; + + continue; + + case EOF: + fatal("unterminated %guard clause"); + + default: + putc(c, fguard); + } + + if (c != '}' || count != 0) + c = getc(finput); + } + + c = skip_white_space(); + + fprintf(fguard, ";\n break;}"); + if (c == '{') + copy_action(rule, stack_offset); + else if (c == '=') + { + c = getc(finput); + if (c == '{') + copy_action(rule, stack_offset); + } + else + ungetc(c, finput); + } + + + + /* Assuming that a { has just been seen, copy everything up to the matching } + into the actions file. + stack_offset is the number of values in the current rule so far, + which says where to find $0 with respect to the top of the stack. */ + + void copy_action(symbol_list *rule,int stack_offset) + { + register int c; + register int n; + register int count; + register int match; + register int ended; + register char *type_name; + extern char token_buffer[]; + + /* offset is always 0 if parser has already popped the stack pointer */ + if (semantic_parser) stack_offset = 0; + + fprintf(faction, "\ncase %d:\n", nrules); + if (!nolinesflag) + fprintf(faction, "#line %d \"%s\"\n", lineno, infile); + putc('{', faction); + + count = 1; + c = getc(finput); + + while (count > 0) + { + while (c != '}') + { + switch (c) + { + case '\n': + putc(c, faction); + lineno++; + break; + + case '{': + putc(c, faction); + count++; + break; + + case '\'': + case '"': + match = c; + putc(c, faction); + c = getc(finput); + + while (c != match) + { + if (c == EOF || c == '\n') + fatal("unterminated string"); + + putc(c, faction); + + if (c == '\\') + { + c = getc(finput); + if (c == EOF) + fatal("unterminated string"); + putc(c, faction); + if (c == '\n') + lineno++; + } + + c = getc(finput); + } + + putc(c, faction); + break; + + case '/': + putc(c, faction); + c = getc(finput); + if (c != '*') + continue; + + putc(c, faction); + c = getc(finput); + + ended = 0; + while (!ended) + { + if (c == '*') + { + while (c == '*') + { + putc(c, faction); + c = getc(finput); + } + + if (c == '/') + { + putc(c, faction); + ended = 1; + } + } + else if (c == '\n') + { + lineno++; + putc(c, faction); + c = getc(finput); + } + else if (c == EOF) + fatal("unterminated comment"); + else + { + putc(c, faction); + c = getc(finput); + } + } + + break; + + case '$': + c = getc(finput); + type_name = NULL; + + if (c == '<') + { + register char *cp = token_buffer; + + while ((c = getc(finput)) != '>' && c > 0) + *cp++ = c; + *cp = 0; + type_name = token_buffer; + + c = getc(finput); + } + if (c == '$') + { + fprintf(faction, "yyval"); + if (!type_name) type_name = get_type_name(0, rule); + if (type_name) + fprintf(faction, ".%s", type_name); + if(!type_name && typed) /* JF */ + fprintf(stderr,"%s:%d: warning: $$ of '%s' has no declared type.\n",infile,lineno,rule->sym->tag); + } + else if (isdigit(c) || c == '-') + { + ungetc (c, finput); + n = read_signed_integer(finput); + c = getc(finput); + + if (!type_name && n > 0) + type_name = get_type_name(n, rule); + + fprintf(faction, "yyp->yyvsp[%d]", n - stack_offset); + if (type_name) + fprintf(faction, ".%s", type_name); + if(!type_name && typed) /* JF */ + fprintf(stderr,"%s:%d: warning: $%d of '%s' has no declared type.\n",infile,lineno,n,rule->sym->tag); + continue; + } + else + fatals("$%c is invalid",c,0,0,0,0,0,0,0); + /* JF changed format */ + + break; + + case '@': + c = getc(finput); + if (isdigit(c) || c == '-') + { + ungetc (c, finput); + n = read_signed_integer(finput); + c = getc(finput); + } + else + fatal("invalid @-construct"); + + fprintf(faction, "yyp->yylsp[%d]", n - stack_offset); + yylsp_needed = 1; + + continue; + + case EOF: + fatal("unmatched '{'"); + + default: + putc(c, faction); + } + + c = getc(finput); + } + + /* above loop exits when c is '}' */ + + if (--count) + { + putc(c, faction); + c = getc(finput); + } + } + + fprintf(faction, ";\n break;}"); + } + + + + /* generate a dummy symbol, a nonterminal, + whose name cannot conflict with the user's names. */ + + bucket *gensym(void) + { + register bucket *sym; + + extern char token_buffer[]; + sprintf (token_buffer, "@%d", ++gensym_count); + sym = getsym(token_buffer); + sym->class = SNTERM; + sym->value = nvars++; + return (sym); + } + + /* Parse the input grammar into a one symbol_list structure. + Each rule is represented by a sequence of symbols: the left hand side + followed by the contents of the right hand side, followed by a null pointer + instead of a symbol to terminate the rule. + The next symbol is the lhs of the following rule. + + All guards and actions are copied out to the appropriate files, + labelled by the rule number they apply to. */ + + void readgram(void) + { + register int t; + register bucket *lhs; + register symbol_list *p; + register symbol_list *p1; + register bucket *bp; + + symbol_list *crule; /* points to first symbol_list of current rule. */ + /* its symbol is the lhs of the rule. */ + symbol_list *crule1; /* points to the symbol_list preceding crule. */ + + p1 = NULL; + + t = lex(); + + while (t != TWO_PERCENTS && t != ENDFILE) + { + if (t == IDENTIFIER || t == BAR) + { + register int actionflag = 0; + int rulelength = 0; /* number of symbols in rhs of this rule so far */ + int xactions = 0; /* JF for error checking */ + bucket *first_rhs = 0; + + if (t == IDENTIFIER) + { + lhs = symval; + + t = lex(); + if (t != COLON) + fatal("ill-formed rule"); + } + + if (nrules == 0) + { + if (t == BAR) + fatal("grammar starts with vertical bar"); + + if (!start_flag) + startval = lhs; + } + + /* start a new rule and record its lhs. */ + + nrules++; + nitems++; + + record_rule_line (); + + p = NEW(symbol_list); + p->sym = lhs; + + crule1 = p1; + if (p1) + p1->next = p; + else + grammar = p; + + p1 = p; + crule = p; + + /* mark the rule's lhs as a nonterminal if not already so. */ + + if (lhs->class == SUNKNOWN) + { + lhs->class = SNTERM; + lhs->value = nvars; + nvars++; + } + else if (lhs->class == STOKEN) + fatals("rule given for %s, which is a token", lhs->tag,0,0,0,0, + 0,0,0); + + /* read the rhs of the rule. */ + + for (;;) + { + t = lex(); + + if (! (t == IDENTIFIER || t == LEFT_CURLY)) break; + + /* if next token is an identifier, see if a colon follows it. + If one does, exit this rule now. */ + if (t == IDENTIFIER) + { + register bucket *ssave; + register int t1; + + ssave = symval; + t1 = lex(); + unlex(t1); + symval = ssave; + if (t1 == COLON) break; + + if(!first_rhs) /* JF */ + first_rhs = symval; + /* not followed by colon => process as part of this rule's rhs. */ + if (actionflag) + { + register bucket *sdummy; + + /* if this symbol was preceded by an action, */ + /* make a dummy nonterminal to replace that action in this rule */ + /* and make another rule to associate the action to the dummy. */ + /* Since the action was written out with this rule's number, */ + /* we must write give the new rule this number */ + /* by inserting the new rule before it. */ + + /* make a dummy nonterminal, a gensym. */ + sdummy = gensym(); + + /* make a new rule, whose body is empty, before the current one. */ + /* so that the action just read can belong to it. */ + nrules++; + nitems++; + record_rule_line (); + p = NEW(symbol_list); + if (crule1) + crule1->next = p; + else grammar = p; + p->sym = sdummy; + crule1 = NEW(symbol_list); + p->next = crule1; + crule1->next = crule; + + /* insert the dummy generated by that rule into this rule. */ + nitems++; + p = NEW(symbol_list); + p->sym = sdummy; + p1->next = p; + p1 = p; + + actionflag = 0; + } + nitems++; + p = NEW(symbol_list); + p->sym = symval; + p1->next = p; + p1 = p; + } + else /* handle an action. */ + { + copy_action(crule, rulelength); + actionflag = 1; + xactions++; /* JF */ + } + rulelength++; + } + + /* Put an empty link in the list to mark the end of this rule */ + p = NEW(symbol_list); + p1->next = p; + p1 = p; + + if (t == PREC) + { + t = lex(); + crule->ruleprec = symval; + t = lex(); + } + if (t == GUARD) + { + if (! semantic_parser) + fatal("%guard present but %semantic_parser not specified"); + + copy_guard(crule, rulelength); + t = lex(); + } + else if (t == LEFT_CURLY) + { + if (actionflag) fatal("two actions at end of one rule"); + copy_action(crule, rulelength); + t = lex(); + } + /* JF if we'd end up using default, get a warning */ + else if(!xactions && first_rhs && lhs->type_name!=first_rhs->type_name) { + if(lhs->type_name == 0 || first_rhs->type_name == 0 || + strcmp(lhs->type_name,first_rhs->type_name)) + fprintf(stderr,"%s:%d: warning: type clash ('%s' '%s') on default action\n", + infile, + lineno, + lhs->type_name ? lhs->type_name : "", + first_rhs->type_name ? first_rhs->type_name : ""); + } + if (t == SEMICOLON) + t = lex(); + } + /* these things can appear as alternatives to rules. */ + else if (t == TOKEN) + { + parse_token_decl(STOKEN, SNTERM); + t = lex(); + } + else if (t == NTERM) + { + parse_token_decl(SNTERM, STOKEN); + t = lex(); + } + else if (t == TYPE) + { + t = get_type(); + } + else if (t == UNION) + { + parse_union_decl(); + t = lex(); + } + else if (t == EXPECT) + { + parse_expect_decl(); + t = lex(); + } + else if (t == START) + { + parse_start_decl(); + t = lex(); + } + else + fatal("invalid input"); + } + + if (nrules == 0) + fatal("no input grammar"); + + if (typed == 0)/* JF put out same default YYSTYPE as YACC does */ + { + fprintf(fattrs, "#ifndef YYSTYPE\n#define YYSTYPE int\n#endif\n"); + if (fdefines) + fprintf(fdefines, "#ifndef YYSTYPE\n#define YYSTYPE int\n#endif\n"); + } + + /* Report any undefined symbols and consider them nonterminals. */ + + for (bp = firstsymbol; bp; bp = bp->next) + if (bp->class == SUNKNOWN) + { + fprintf(stderr, "symbol %s used, not defined as token, and no rules for it\n", + bp->tag); + failure = 1; + bp->class = SNTERM; + bp->value = nvars++; + } + + ntokens = nsyms - nvars; + } + + + void record_rule_line(void) + { + /* Record each rule's source line number in rline table. */ + + if (nrules >= rline_allocated) + { + rline_allocated = nrules * 2; + rline = (short *) realloc (rline, + rline_allocated * sizeof (short)); + if (rline == 0) + { + fprintf (stderr, "bison: memory exhausted\n"); + done (1); + } + } + rline[nrules] = lineno; + } + + /* read in a %type declaration and record its information for get_type_name to access */ + + int get_type(void) + { + register int k; + register int t; + register char *name; + + extern char token_buffer[]; + + t = lex(); + + if (t != TYPENAME) + fatal("ill-formed %type declaration"); + + k = strlen(token_buffer); + name = NEW2(k + 1, char); + strcpy(name, token_buffer); + + for (;;) + { + t = lex(); + + switch (t) + { + case SEMICOLON: + return (lex()); + + case COMMA: + break; + + case IDENTIFIER: + if (symval->type_name == NULL) + symval->type_name = name; + else + fatals("type redeclaration for %s", symval->tag,0,0,0,0,0,0,0); + + break; + + default: + return (t); + } + } + } + + /* assign symbol numbers, and write definition of token names into fdefines. + Set up vectors tags and sprec of names and precedences of symbols. */ + + void packsymbols(void) + { + register bucket *bp; + register int tokno = 1; + register int i; + register int last_user_token_number; + + /* int lossage = 0; JF set but not used */ + + tags = NEW2(nsyms + 1, char *); + tags[0] = "$"; + + sprec = NEW2(nsyms, short); + sassoc = NEW2(nsyms, short); + + max_user_token_number = 255; + last_user_token_number = 255; + + for (bp = firstsymbol; bp; bp = bp->next) + { + if (bp->class == SNTERM) + { + bp->value += ntokens; + } + else + { + if (translations && !(bp->user_token_number)) + bp->user_token_number = ++last_user_token_number; + if (bp->user_token_number > max_user_token_number) + max_user_token_number = bp->user_token_number; + bp->value = tokno++; + } + + tags[bp->value] = bp->tag; + sprec[bp->value] = bp->prec; + sassoc[bp->value] = bp->assoc; + + } + + if (translations) + { + register int i; + + token_translations = NEW2(max_user_token_number+1, short); + + /* initialize all entries for literal tokens to 2, + the internal token number for $illegal., which represents all invalid inputs. */ + for (i = 0; i <= max_user_token_number; i++) + token_translations[i] = 2; + } + + for (bp = firstsymbol; bp; bp = bp->next) + { + if (bp->value >= ntokens) continue; + if (translations) + { + if (token_translations[bp->user_token_number] != 2) + { + /* JF made this a call to fatals() */ + fatals( "tokens %s and %s both assigned number %d", + tags[token_translations[bp->user_token_number]], + bp->tag, + bp->user_token_number,0,0,0,0,0); + } + token_translations[bp->user_token_number] = bp->value; + } + } + + error_token_number = errtoken->value; + + output_token_defines(ftable); + + if (startval->class == SUNKNOWN) + fatals("the start symbol %s is undefined", startval->tag,0,0,0,0,0,0,0); + else if (startval->class == STOKEN) + fatals("the start symbol %s is a token", startval->tag,0,0,0,0,0,0,0); + + start_symbol = startval->value; + + if (definesflag) + { + output_token_defines(fdefines); + + if (semantic_parser) + for (i = ntokens; i < nsyms; i++) + { + /* don't make these for dummy nonterminals made by gensym. */ + if (*tags[i] != '@') + fprintf(fdefines, "#define\tNT%s\t%d\n", tags[i], i); + } + + fclose(fdefines); + fdefines = NULL; + } + } + + void output_token_defines(FILE *file) + { + bucket *bp; + + for (bp = firstsymbol; bp; bp = bp->next) + { + if (bp->value >= ntokens) continue; + + /* For named tokens, but not literal ones, define the name. */ + /* The value is the user token number. */ + + if ('\'' != *tags[bp->value] && bp != errtoken) + { + register char *cp = tags[bp->value]; + register char c; + + /* Don't #define nonliteral tokens whose names contain periods. */ + + while ((c = *cp++) && c != '.'); + if (!c) + { + fprintf(file, "#define\t%s\t%d\n", tags[bp->value], + (translations ? bp->user_token_number : bp->value)); + if (semantic_parser) + fprintf(file, "#define\tT%s\t%d\n", tags[bp->value], + bp->value); + } + } + } + + putc('\n', file); + } + + /* convert the rules into the representation using rrhs, rlhs and ritems. */ + + void packgram(void) + { + register int itemno; + register int ruleno; + register symbol_list *p; + /* register bucket *bp; JF unused */ + + bucket *ruleprec; + + ritem = NEW2(nitems + 1, short); + rlhs = NEW2(nrules, short) - 1; + rrhs = NEW2(nrules, short) - 1; + rprec = NEW2(nrules, short) - 1; + rassoc = NEW2(nrules, short) - 1; + + itemno = 0; + ruleno = 1; + + p = grammar; + while (p) + { + rlhs[ruleno] = p->sym->value; + rrhs[ruleno] = itemno; + ruleprec = p->ruleprec; + + p = p->next; + while (p && p->sym) + { + ritem[itemno++] = p->sym->value; + /* a rule gets the precedence and associativity of the last token in it. */ + if (p->sym->class == STOKEN) + { + rprec[ruleno] = p->sym->prec; + rassoc[ruleno] = p->sym->assoc; + } + if (p) p = p->next; + } + + /* if this rule has a %prec, specified symbol's precedence replaces the default */ + if (ruleprec) + { + rprec[ruleno] = ruleprec->prec; + rassoc[ruleno] = ruleprec->assoc; + } + + ritem[itemno++] = -ruleno; + ruleno++; + + if (p) p = p->next; + } + + ritem[itemno] = 0; + } + + /* Read a signed integer from STREAM and return its value. */ + + int read_signed_integer(FILE *stream) + { + register int c = getc(stream); + register int sign = 1; + register int n; + + if (c == '-') + { + c = getc(stream); + sign = -1; + } + n = 0; + while (isdigit(c)) + { + n = 10*n + (c - '0'); + c = getc(stream); + } + + ungetc(c, stream); + + return n * sign; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/state.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/state.h:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/state.h Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,137 ---- + /* Type definitions for nondeterministic finite state machine for bison, + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + /* These type definitions are used to represent a nondeterministic + finite state machine that parses the specified grammar. + This information is generated by the function generate_states + in the file LR0. + + Each state of the machine is described by a set of items -- + particular positions in particular rules -- that are the possible + places where parsing could continue when the machine is in this state. + These symbols at these items are the allowable inputs that can follow now. + + A core represents one state. States are numbered in the number field. + When generate_states is finished, the starting state is state 0 + and nstates is the number of states. (A transition to a state + whose state number is nstates indicates termination.) All the cores + are chained together and first_state points to the first one (state 0). + + For each state there is a particular symbol which must have been the + last thing accepted to reach that state. It is the accessing_symbol + of the core. + + Each core contains a vector of nitems items which are the indices + in the ritems vector of the items that are selected in this state. + + The link field is used for chaining buckets that hash states by + their itemsets. This is for recognizing equivalent states and + combining them when the states are generated. + + The two types of transitions are shifts (push the lookahead token + and read another) and reductions (combine the last n things on the + stack via a rule, replace them with the symbol that the rule derives, + and leave the lookahead token alone). When the states are generated, + these transitions are represented in two other lists. + + Each shifts structure describes the possible shift transitions out + of one state, the state whose number is in the number field. + The shifts structures are linked through next and first_shift points to them. + Each contains a vector of numbers of the states that shift transitions + can go to. The accessing_symbol fields of those states' cores say what kind + of input leads to them. + + A shift to state zero should be ignored. Conflict resolution + deletes shifts by changing them to zero. + + Each reductions structure describes the possible reductions at the state + whose number is in the number field. The data is a list of nreds rules, + represented by their rule numbers. first_reduction points to the list + of these structures. + + Conflict resolution can decide that certain tokens in certain + states should explicitly be errors (for implementing %nonassoc). + For each state, the tokens that are errors for this reason + are recorded in an errs structure, which has the state number + in its number field. The rest of the errs structure is full + of token numbers. + + There is at least one shift transition present in state zero. + It leads to a next-to-final state whose accessing_symbol is + the grammar's start symbol. The next-to-final state has one shift + to the final state, whose accessing_symbol is zero (end of input). + The final state has one shift, which goes to the termination state + (whose number is nstates, and for which there is no core structure). + The reason for the extra state at the end is to placate the parser's + strategy of making all decisions one token ahead of its actions. */ + + + typedef + struct core + { + struct core *next; + struct core *link; + short number; + short accessing_symbol; + short nitems; + short items[1]; + } + core; + + + + typedef + struct shifts + { + struct shifts *next; + short number; + short nshifts; + short shifts[1]; + } + shifts; + + + + typedef + struct errs + { + short nerrs; + short errs[1]; + } + errs; + + + + typedef + struct reductions + { + struct reductions *next; + short number; + short nreds; + short rules[1]; + } + reductions; + + + + extern int nstates; + extern core *first_state; + extern shifts *first_shift; + extern reductions *first_reduction; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/symtab.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/symtab.c:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/symtab.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,139 ---- + /* Symbol table manager for Bison, + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + #include + #ifdef USG + #include + #else /* NOT USG */ + #include + #endif /* NOT USG */ + + #include "new.h" + #include "symtab.h" + #include "gram.h" + + + bucket **symtab; + bucket *firstsymbol; + bucket *lastsymbol; + + + + int hash(char *key) + { + register char *cp; + register int k; + + cp = key; + k = 0; + while (*cp) + k = ((k << 1) ^ (*cp++)) & 0x3fff; + + return (k % TABSIZE); + } + + + + char *copys(char *s) + { + register int i; + register char *cp; + register char *result; + + i = 1; + for (cp = s; *cp; cp++) + i++; + + result = mallocate((unsigned int)i); + strcpy(result, s); + return (result); + } + + void tabinit(void) + { + /* register int i; JF unused */ + + symtab = NEW2(TABSIZE, bucket *); + + firstsymbol = NULL; + lastsymbol = NULL; + } + + bucket *getsym(char *key) + { + register int hashval; + register bucket *bp; + register int found; + + hashval = hash(key); + bp = symtab[hashval]; + + found = 0; + while (bp != NULL && found == 0) + { + if (strcmp(key, bp->tag) == 0) + found = 1; + else + bp = bp->link; + } + + if (found == 0) + { + nsyms++; + + bp = NEW(bucket); + bp->link = symtab[hashval]; + bp->next = NULL; + bp->tag = copys(key); + bp->class = SUNKNOWN; + + if (firstsymbol == NULL) + { + firstsymbol = bp; + lastsymbol = bp; + } + else + { + lastsymbol->next = bp; + lastsymbol = bp; + } + + symtab[hashval] = bp; + } + + return (bp); + } + + void free_symtab(void) + { + register int i; + register bucket *bp,*bptmp;/* JF don't use ptr after free */ + + for (i = 0; i < TABSIZE; i++) + { + bp = symtab[i]; + while (bp) + { + bptmp=bp->link; + FREE(bp); + bp = bptmp; + } + } + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/symtab.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/symtab.h:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/symtab.h Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,50 ---- + /* Definitions for symtab.c and callers, part of bison, + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + #define TABSIZE 1009 + + + /* symbol classes */ + + #define SUNKNOWN 0 + #define STOKEN 1 + #define SNTERM 2 + + + typedef + struct bucket + { + struct bucket *link; + struct bucket *next; + char *tag; + char *type_name; + short value; + short prec; + short assoc; + short user_token_number; + char class; + } + bucket; + + + extern bucket **symtab; + extern bucket *firstsymbol; + + extern bucket *getsym(); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/types.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/types.h:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/types.h Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,27 ---- + /* Define data type for representing bison's grammar input as it is parsed, + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + typedef + struct shorts + { + struct shorts *next; + short value; + } + shorts; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/warshall.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/warshall.c:1.1 *** /dev/null Tue Oct 5 13:32:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/warshall.c Tue Oct 5 13:31:50 2004 *************** *** 0 **** --- 1,112 ---- + /* Generate transitive closure of a matrix, + Copyright (C) 1984 Bob Corbett and Free Software Foundation, Inc. + + BISON is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone + for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the BISON General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute BISON, + but only under the conditions described in the BISON General Public + License. A copy of this license is supposed to have been given to you + along with BISON so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. + + In other words, you are welcome to use, share and improve this program. + You are forbidden to forbid anyone else to use, share and improve + what you give them. Help stamp out software-hoarding! */ + + #include + #include "machine.h" + + + /* given n by n matrix of bits R, modify its contents + to be the transive closure of what was given. */ + + void TC(unsigned *R,int n) + { + register int rowsize; + register unsigned mask; + register unsigned *rowj; + register unsigned *rp; + register unsigned *rend; + register unsigned *ccol; + + unsigned *relend; + unsigned *cword; + unsigned *rowi; + + rowsize = WORDSIZE(n) * sizeof(unsigned); + relend = (unsigned *) ((char *) R + (n * rowsize)); + + cword = R; + mask = 1; + rowi = R; + while (rowi < relend) + { + ccol = cword; + rowj = R; + + while (rowj < relend) + { + if (*ccol & mask) + { + rp = rowi; + rend = (unsigned *) ((char *) rowj + rowsize); + + while (rowj < rend) + *rowj++ |= *rp++; + } + else + { + rowj = (unsigned *) ((char *) rowj + rowsize); + } + + ccol = (unsigned *) ((char *) ccol + rowsize); + } + + mask <<= 1; + if (mask == 0) + { + mask = 1; + cword++; + } + + rowi = (unsigned *) ((char *) rowi + rowsize); + } + } + + + /* Reflexive Transitive Closure. Same as TC + and then set all the bits on the diagonal of R. */ + + void RTC(unsigned *R,int n) + { + register int rowsize; + register unsigned mask; + register unsigned *rp; + register unsigned *relend; + + TC(R, n); + + rowsize = WORDSIZE(n) * sizeof(unsigned); + relend = (unsigned *) ((char *) R + n*rowsize); + + mask = 1; + rp = R; + while (rp < relend) + { + *rp |= mask; + + mask <<= 1; + if (mask == 0) + { + mask = 1; + rp++; + } + + rp = (unsigned *) ((char *) rp + rowsize); + } + } From brukman at cs.uiuc.edu Tue Oct 5 13:36:57 2004 From: brukman at cs.uiuc.edu (Misha Brukman) Date: Tue, 5 Oct 2004 13:36:57 -0500 Subject: [llvm-commits] CVS: llvm-tv/include/Support/FileUtils.h Snapshots.h Message-ID: <200410051836.NAA14787@zion.cs.uiuc.edu> Changes in directory llvm-tv/include/Support: FileUtils.h (r1.4) removed Snapshots.h (r1.1) removed --- Log message: Files moved to include/llvm-tv/Support --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 13:37:58 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 13:37:58 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/Makefile files.c Message-ID: <200410051837.NAA23085@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/bison: Makefile updated: 1.1 -> 1.2 files.c updated: 1.1 -> 1.2 --- Log message: Make it run --- Diffs of the changes: (+11 -9) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/Makefile diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/Makefile:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/Makefile:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/Makefile:1.1 Tue Oct 5 13:31:49 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/Makefile Tue Oct 5 13:37:45 2004 @@ -1,5 +1,6 @@ LEVEL = ../../../.. PROG = mybison +RUN_OPTIONS = $(BUILD_SRC_DIR)/parse.y.in -v include $(LEVEL)/MultiSource/Makefile.multisrc Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/files.c diff -u llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/files.c:1.1 llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/files.c:1.2 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/files.c:1.1 Tue Oct 5 13:31:50 2004 +++ llvm-test/MultiSource/Benchmarks/Prolangs-C/bison/files.c Tue Oct 5 13:37:45 2004 @@ -162,26 +162,26 @@ if (verboseflag) { outfile = stringappend(name_base, short_base_length, ".output"); - foutput = tryopen(outfile, "w"); + foutput = stdout; /*tryopen(outfile, "w");*/ } if (definesflag) { defsfile = stringappend(name_base, base_length, ".h"); - fdefines = tryopen(defsfile, "w"); + fdefines = stdout; /*tryopen(defsfile, "w");*/ } actfile = mktemp(stringappend(tmp_base, tmp_len, "act.XXXXXX")); - faction = tryopen(actfile, "w+"); - unlink(actfile); + faction = stdout; /*tryopen(actfile, "w+"); + unlink(actfile);*/ tmpattrsfile = mktemp(stringappend(tmp_base, tmp_len, "attrs.XXXXXX")); - fattrs = tryopen(tmpattrsfile,"w+"); - unlink(tmpattrsfile); + fattrs = stdout; /*tryopen(tmpattrsfile,"w+"); + unlink(tmpattrsfile);*/ tmptabfile = mktemp(stringappend(tmp_base, tmp_len, "tab.XXXXXX")); - ftable = tryopen(tmptabfile, "w+"); - unlink(tmptabfile); + ftable = stdout; /*tryopen(tmptabfile, "w+"); + unlink(tmptabfile);*/ /* These are opened by `done' or `open_extra_files', if at all */ if (spec_outfile) @@ -218,7 +218,7 @@ rewind(fattrs); while((c=getc(fattrs))!=EOF) /* Thank god for buffering */ putc(c,ftmp); - fclose(fattrs); + /*fclose(fattrs);*/ fattrs=ftmp; fguard = tryopen(guardfile, "w"); @@ -243,6 +243,7 @@ void done(int k) { + return; if (faction) fclose(faction); From brukman at cs.uiuc.edu Tue Oct 5 13:38:36 2004 From: brukman at cs.uiuc.edu (Misha Brukman) Date: Tue, 5 Oct 2004 13:38:36 -0500 Subject: [llvm-commits] CVS: llvm-tv/lib/Snapshot/FileUtils.cpp ReadSnapshots.cpp WriteSnapshot.cpp Message-ID: <200410051838.NAA15108@zion.cs.uiuc.edu> Changes in directory llvm-tv/lib/Snapshot: FileUtils.cpp updated: 1.5 -> 1.6 ReadSnapshots.cpp updated: 1.2 -> 1.3 WriteSnapshot.cpp updated: 1.9 -> 1.10 --- Log message: Adjust for #include file being moved and PassManager API change. --- Diffs of the changes: (+15 -14) Index: llvm-tv/lib/Snapshot/FileUtils.cpp diff -u llvm-tv/lib/Snapshot/FileUtils.cpp:1.5 llvm-tv/lib/Snapshot/FileUtils.cpp:1.6 --- llvm-tv/lib/Snapshot/FileUtils.cpp:1.5 Sat May 15 00:48:22 2004 +++ llvm-tv/lib/Snapshot/FileUtils.cpp Tue Oct 5 13:38:25 2004 @@ -12,7 +12,7 @@ // //===----------------------------------------------------------------------===// -#include "Support/FileUtils.h" +#include "llvm-tv/Support/FileUtils.h" #include #include #include Index: llvm-tv/lib/Snapshot/ReadSnapshots.cpp diff -u llvm-tv/lib/Snapshot/ReadSnapshots.cpp:1.2 llvm-tv/lib/Snapshot/ReadSnapshots.cpp:1.3 --- llvm-tv/lib/Snapshot/ReadSnapshots.cpp:1.2 Tue Apr 13 13:36:21 2004 +++ llvm-tv/lib/Snapshot/ReadSnapshots.cpp Tue Oct 5 13:38:25 2004 @@ -12,8 +12,8 @@ #include "llvm/Module.h" #include "llvm/Bytecode/Reader.h" -#include "Support/FileUtils.h" -#include "Support/Snapshots.h" +#include "llvm-tv/Support/FileUtils.h" +#include "llvm-tv/Support/Snapshots.h" #include #include using namespace llvm; Index: llvm-tv/lib/Snapshot/WriteSnapshot.cpp diff -u llvm-tv/lib/Snapshot/WriteSnapshot.cpp:1.9 llvm-tv/lib/Snapshot/WriteSnapshot.cpp:1.10 --- llvm-tv/lib/Snapshot/WriteSnapshot.cpp:1.9 Sat May 15 00:48:33 2004 +++ llvm-tv/lib/Snapshot/WriteSnapshot.cpp Tue Oct 5 13:38:25 2004 @@ -16,12 +16,12 @@ #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Bytecode/WriteBytecodePass.h" +#include "llvm/ADT/StringExtras.h" +#include "llvm/Support/CommandLine.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/SystemUtils.h" +#include "llvm-tv/Support/FileUtils.h" #include "llvm-tv/Config.h" -#include "Support/CommandLine.h" -#include "Support/Debug.h" -#include "Support/FileUtils.h" -#include "Support/StringExtras.h" -#include "Support/SystemUtils.h" #include #include #ifndef _GNU_SOURCE @@ -46,8 +46,9 @@ AU.setPreservesAll(); } - /// run - save the Module in a pre-defined location with our naming strategy - bool run(Module &M); + /// runPass - save the Module in a pre-defined location with our naming + /// strategy + bool runPass(Module &M); private: bool sendSignalToLLVMTV(); @@ -63,11 +64,11 @@ } -/// run - save snapshot to a pre-defined directory with a consecutive number in -/// the name (for alphabetization) and the name of the pass that ran just before -/// this one. Signal llvm-tv that fresh bytecode file has arrived for +/// runPass - save snapshot to a pre-defined directory with a consecutive number +/// in the name (for alphabetization) and the name of the pass that ran just +/// before this one. Signal llvm-tv that fresh bytecode file has arrived for /// consumption. -bool Snapshot::run(Module &M) { +bool Snapshot::runPass(Module &M) { // Make sure the snapshots dir exists, which it will unless this // is the first time we've ever run the -snapshot pass. EnsureDirectoryExists (llvmtvPath); From brukman at cs.uiuc.edu Tue Oct 5 13:44:55 2004 From: brukman at cs.uiuc.edu (Misha Brukman) Date: Tue, 5 Oct 2004 13:44:55 -0500 Subject: [llvm-commits] CVS: llvm-tv/tools/llvm-tv/CodeViewer.cpp GraphDrawer.cpp GraphPrinters.cpp HTMLPrinterUtils.cpp TVApplication.cpp Message-ID: <200410051844.NAA16465@zion.cs.uiuc.edu> Changes in directory llvm-tv/tools/llvm-tv: CodeViewer.cpp updated: 1.9 -> 1.10 GraphDrawer.cpp updated: 1.5 -> 1.6 GraphPrinters.cpp updated: 1.5 -> 1.6 HTMLPrinterUtils.cpp updated: 1.3 -> 1.4 TVApplication.cpp updated: 1.27 -> 1.28 --- Log message: Adjust for changes in LLVM .h file locations and structure --- Diffs of the changes: (+7 -11) Index: llvm-tv/tools/llvm-tv/CodeViewer.cpp diff -u llvm-tv/tools/llvm-tv/CodeViewer.cpp:1.9 llvm-tv/tools/llvm-tv/CodeViewer.cpp:1.10 --- llvm-tv/tools/llvm-tv/CodeViewer.cpp:1.9 Wed May 12 21:11:50 2004 +++ llvm-tv/tools/llvm-tv/CodeViewer.cpp Tue Oct 5 13:44:44 2004 @@ -5,7 +5,7 @@ #include "llvm/Function.h" #include "llvm/Instruction.h" #include "llvm/Value.h" -#include "Support/StringExtras.h" +#include "llvm/ADT/StringExtras.h" #include #include #include Index: llvm-tv/tools/llvm-tv/GraphDrawer.cpp diff -u llvm-tv/tools/llvm-tv/GraphDrawer.cpp:1.5 llvm-tv/tools/llvm-tv/GraphDrawer.cpp:1.6 --- llvm-tv/tools/llvm-tv/GraphDrawer.cpp:1.5 Thu May 6 02:19:49 2004 +++ llvm-tv/tools/llvm-tv/GraphDrawer.cpp Tue Oct 5 13:44:44 2004 @@ -1,7 +1,7 @@ #include "wx/image.h" #include "GraphDrawer.h" #include "TVTreeItem.h" -#include "Support/FileUtilities.h" +#include "llvm/Support/FileUtilities.h" #include #include using namespace llvm; Index: llvm-tv/tools/llvm-tv/GraphPrinters.cpp diff -u llvm-tv/tools/llvm-tv/GraphPrinters.cpp:1.5 llvm-tv/tools/llvm-tv/GraphPrinters.cpp:1.6 --- llvm-tv/tools/llvm-tv/GraphPrinters.cpp:1.5 Thu Jul 15 16:20:50 2004 +++ llvm-tv/tools/llvm-tv/GraphPrinters.cpp Tue Oct 5 13:44:44 2004 @@ -20,7 +20,7 @@ #include "llvm/Analysis/CallGraph.h" #include "llvm/Analysis/DataStructure/DataStructure.h" #include "llvm/Analysis/DataStructure/DSGraph.h" -#include "Support/GraphWriter.h" +#include "llvm/Support/GraphWriter.h" #include using namespace llvm; Index: llvm-tv/tools/llvm-tv/HTMLPrinterUtils.cpp diff -u llvm-tv/tools/llvm-tv/HTMLPrinterUtils.cpp:1.3 llvm-tv/tools/llvm-tv/HTMLPrinterUtils.cpp:1.4 --- llvm-tv/tools/llvm-tv/HTMLPrinterUtils.cpp:1.3 Thu Jun 10 08:21:25 2004 +++ llvm-tv/tools/llvm-tv/HTMLPrinterUtils.cpp Tue Oct 5 13:44:44 2004 @@ -5,18 +5,14 @@ #include "llvm/Assembly/AsmAnnotationWriter.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" -#include "llvm/Instruction.h" -#include "llvm/iMemory.h" -#include "llvm/iTerminators.h" -#include "llvm/iPHINode.h" -#include "llvm/iOther.h" +#include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/SymbolTable.h" #include "llvm/Analysis/SlotCalculator.h" #include "llvm/Assembly/Writer.h" #include "llvm/Support/CFG.h" -#include "Support/StringExtras.h" -#include "Support/STLExtras.h" +#include "llvm/ADT/StringExtras.h" +#include "llvm/Support/STLExtras.h" #include using namespace llvm; Index: llvm-tv/tools/llvm-tv/TVApplication.cpp diff -u llvm-tv/tools/llvm-tv/TVApplication.cpp:1.27 llvm-tv/tools/llvm-tv/TVApplication.cpp:1.28 --- llvm-tv/tools/llvm-tv/TVApplication.cpp:1.27 Thu Jul 15 16:21:01 2004 +++ llvm-tv/tools/llvm-tv/TVApplication.cpp Tue Oct 5 13:44:44 2004 @@ -7,7 +7,7 @@ #include "CodeViewer.h" #include "TVApplication.h" #include "TVFrame.h" -#include "Support/FileUtils.h" +#include "llvm-tv/Support/FileUtils.h" #include "llvm-tv/Config.h" #include #include From gaeke at cs.uiuc.edu Tue Oct 5 13:47:10 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Tue, 5 Oct 2004 13:47:10 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/Unix/MappedFile.cpp Message-ID: <200410051847.NAA16930@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/Unix: MappedFile.cpp updated: 1.3 -> 1.4 --- Log message: Must include sys/stat.h before declaring a 'struct stat' --- Diffs of the changes: (+1 -0) Index: llvm/lib/System/Unix/MappedFile.cpp diff -u llvm/lib/System/Unix/MappedFile.cpp:1.3 llvm/lib/System/Unix/MappedFile.cpp:1.4 --- llvm/lib/System/Unix/MappedFile.cpp:1.3 Mon Oct 4 19:51:26 2004 +++ llvm/lib/System/Unix/MappedFile.cpp Tue Oct 5 13:46:59 2004 @@ -20,6 +20,7 @@ #include "Unix.h" #include #include +#include namespace llvm { using namespace sys; From lattner at cs.uiuc.edu Tue Oct 5 14:08:26 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 14:08:26 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/ Message-ID: <200410051908.OAA23719@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 14:08:40 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 14:08:40 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/Makefile cdecl.c cdgram.c.source cdgram.y.in cdlex.c.source cdlex.l.in testset Message-ID: <200410051908.OAA23747@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl: Makefile added (r1.1) cdecl.c added (r1.1) cdgram.c.source added (r1.1) cdgram.y.in added (r1.1) cdlex.c.source added (r1.1) cdlex.l.in added (r1.1) testset added (r1.1) --- Log message: New benchmark --- Diffs of the changes: (+4888 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/Makefile:1.1 *** /dev/null Tue Oct 5 14:08:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/Makefile Tue Oct 5 14:08:26 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = cdecl + STDIN_FILENAME = $(SourceDir)/testset + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdecl.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdecl.c:1.1 *** /dev/null Tue Oct 5 14:08:39 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdecl.c Tue Oct 5 14:08:26 2004 *************** *** 0 **** --- 1,1022 ---- + /* + * cdecl - ANSI C and C++ declaration composer & decoder + * + * originally written + * Graham Ross + * once at tektronix!tekmdp!grahamr + * now at Context, Inc. + * + * modified to provide hints for unsupported types + * added argument lists for functions + * added 'explain cast' grammar + * added #ifdef for 'create program' feature + * ???? (sorry, I lost your name and login) + * + * conversion to ANSI C + * David Wolverton + * ihnp4!houxs!daw + * + * merged D. Wolverton's ANSI C version w/ ????'s version + * added function prototypes + * added C++ declarations + * made type combination checking table driven + * added checks for void variable combinations + * made 'create program' feature a runtime option + * added file parsing as well as just stdin + * added help message at beginning + * added prompts when on a TTY or in interactive mode + * added getopt() usage + * added -a, -r, -p, -c, -d, -D, -V, -i and -+ options + * delinted + * added #defines for those without getopt or void + * added 'set options' command + * added 'quit/exit' command + * added synonyms + * Tony Hansen + * attmail!tony, ihnp4!pegasus!hansen + * + * added extern, register, static + * added links to explain, cast, declare + * separately developed ANSI C support + * Merlyn LeRoy + * merlyn at rose3.rosemount.com + * + * merged versions from LeRoy + * added tmpfile() support + * allow more parts to be missing during explanations + * Tony Hansen + * attmail!tony, ihnp4!pegasus!hansen + */ + + char cdeclsccsid[] = "@(#)cdecl.c 2.4 3/31/88"; + + #include + + #include + #if __STDC__ || defined(DOS) + # include + # include + # include + # include + #else + # ifndef NOVARARGS + # include + # endif /* ndef NOVARARGS */ + char *malloc(); + void free(), exit(), perror(); + # ifdef BSD + # include + extern int errno; + # define strrchr rindex + # define NOTMPFILE + # else + # include + # include + # endif /* BSD */ + # ifdef NOVOID + # define void int + # endif /* NOVOID */ + #endif /* __STDC__ || DOS */ + + #include + + #define MB_SHORT 0001 + #define MB_LONG 0002 + #define MB_UNSIGNED 0004 + #define MB_INT 0010 + #define MB_CHAR 0020 + #define MB_FLOAT 0040 + #define MB_DOUBLE 0100 + #define MB_VOID 0200 + #define MB_SIGNED 0400 + + #define NullCP ((char*)NULL) + #ifdef dodebug + # define Debug(x) do { if (DebugFlag) (void) fprintf x; } while (0) + #else + # define Debug(x) /* nothing */ + #endif + + #if __STDC__ + char *ds(char *), *cat(char *, ...), *visible(int); + int getopt(int,char **,char *); + int main(int, char **); + int yywrap_nasko(void); + int dostdin(void); + void mbcheck(void), dohelp(void), usage(void); + void prompt(void), doprompt(void), noprompt(void); + void unsupp(char *, char *); + void notsupported(char *, char *, char *); + void yyerror(char *); + void doset(char *); + void dodeclare(char*, char*, char*, char*, char*); + void docast(char*, char*, char*, char*); + void dodexplain(char*, char*, char*, char*); + void docexplain(char*, char*, char*, char*); + void setprogname(char *); + int dotmpfile(int, char**), dofileargs(int, char**); + #else + char *ds(), *cat(), *visible(); + int getopt(); + void mbcheck(), dohelp(), usage(); + void prompt(), doprompt(), noprompt(); + void unsupp(), notsupported(); + void yyerror(); + void doset(), dodeclare(), docast(), dodexplain(), docexplain(); + void setprogname(); + int dotmpfile(), dofileargs(); + #endif /* __STDC__ */ + FILE *tmpfile(); + + /* variables used during parsing */ + unsigned modbits = 0; + int arbdims = 1; + char *savedname = 0; + char unknown_name[] = "unknown_name"; + char prev = 0; /* the current type of the variable being examined */ + /* values type */ + /* p pointer */ + /* r reference */ + /* f function */ + /* a array (of arbitrary dimensions) */ + /* A array with dimensions */ + /* n name */ + /* v void */ + /* s struct | class */ + /* t simple type (int, long, etc.) */ + + /* options */ + int RitchieFlag = 0; /* -r, assume Ritchie PDP C language */ + int MkProgramFlag = 0; /* -c, output {} and ; after declarations */ + int PreANSIFlag = 0; /* -p, assume pre-ANSI C language */ + int CplusplusFlag = 0; /* -+, assume C++ language */ + int OnATty = 0; /* stdin is coming from a terminal */ + int Interactive = 0; /* -i, overrides OnATty */ + int KeywordName = 0; /* $0 is a keyword (declare, explain, cast) */ + char *progname = "cdecl"; /* $0 */ + + #if dodebug + int DebugFlag = 0; /* -d, output debugging trace info */ + #endif + + #ifdef doyydebug /* compile in yacc trace statements */ + #define YYDEBUG 1 + #endif /* doyydebug */ + + #include "cdgram.c.source" + #include "cdlex.c.source" + + /* definitions (and abbreviations) for type combinations cross check table */ + #define ALWAYS 0 /* combo always okay */ + #define _ ALWAYS + #define NEVER 1 /* combo never allowed */ + #define X NEVER + #define RITCHIE 2 /* combo not allowed in Ritchie compiler */ + #define R RITCHIE + #define PREANSI 3 /* combo not allowed in Pre-ANSI compiler */ + #define P PREANSI + #define ANSI 4 /* combo not allowed anymore in ANSI compiler */ + #define A ANSI + + /* This is an lower left triangular array. If we needed */ + /* to save 9 bytes, the "long" row can be removed. */ + char crosscheck[9][9] = { + /* L, I, S, C, V, U, S, F, D, */ + /* long */ _, _, _, _, _, _, _, _, _, + /* int */ _, _, _, _, _, _, _, _, _, + /* short */ X, _, _, _, _, _, _, _, _, + /* char */ X, X, X, _, _, _, _, _, _, + /* void */ X, X, X, X, _, _, _, _, _, + /* unsigned */ R, _, R, R, X, _, _, _, _, + /* signed */ P, P, P, P, X, X, _, _, _, + /* float */ A, X, X, X, X, X, X, _, _, + /* double */ P, X, X, X, X, X, X, X, _ + }; + + /* the names and bits checked for each row in the above array */ + struct + { + char *name; + int bit; + } crosstypes[9] = + { + { "long", MB_LONG }, + { "int", MB_INT }, + { "short", MB_SHORT }, + { "char", MB_CHAR }, + { "void", MB_VOID }, + { "unsigned", MB_UNSIGNED }, + { "signed", MB_SIGNED }, + { "float", MB_FLOAT }, + { "double", MB_DOUBLE } + }; + + /* Run through the crosscheck array looking */ + /* for unsupported combinations of types. */ + void mbcheck() + { + register int i, j, restrict; + char *t1, *t2; + + /* Loop through the types */ + /* (skip the "long" row) */ + for (i = 1; i < 9; i++) + { + /* if this type is in use */ + if ((modbits & crosstypes[i].bit) != 0) + { + /* check for other types also in use */ + for (j = 0; j < i; j++) + { + /* this type is not in use */ + if (!(modbits & crosstypes[j].bit)) + continue; + /* check the type of restriction */ + restrict = crosscheck[i][j]; + if (restrict == ALWAYS) + continue; + t1 = crosstypes[i].name; + t2 = crosstypes[j].name; + if (restrict == NEVER) + { + notsupported("", t1, t2); + } + else if (restrict == RITCHIE) + { + if (RitchieFlag) + notsupported(" (Ritchie Compiler)", t1, t2); + } + else if (restrict == PREANSI) + { + if (PreANSIFlag || RitchieFlag) + notsupported(" (Pre-ANSI Compiler)", t1, t2); + } + else if (restrict == ANSI) + { + if (!RitchieFlag && !PreANSIFlag) + notsupported(" (ANSI Compiler)", t1, t2); + } + else + { + (void) fprintf (stderr, + "%s: Internal error in crosscheck[%d,%d]=%d!\n", + progname, i, j, restrict); + exit(1); /* NOTREACHED */ + } + } + } + } + } + + /* undefine these as they are no longer needed */ + #undef _ + #undef ALWAYS + #undef X + #undef NEVER + #undef R + #undef RITCHIE + #undef P + #undef PREANSI + #undef A + #undef ANSI + + /* Write out a message about something */ + /* being unsupported, possibly with a hint. */ + void unsupp(s,hint) + char *s,*hint; + { + notsupported("", s, NullCP); + if (hint) + (void) fprintf(stderr, "\t(maybe you mean \"%s\")\n", hint); + } + + /* Write out a message about something */ + /* being unsupported on a particular compiler. */ + void notsupported(compiler, type1, type2) + char *compiler, *type1, *type2; + { + if (type2) + (void) fprintf(stderr, + "Warning: Unsupported in%s C%s -- '%s' with '%s'\n", + compiler, CplusplusFlag ? "++" : "", type1, type2); + else + (void) fprintf(stderr, + "Warning: Unsupported in%s C%s -- '%s'\n", + compiler, CplusplusFlag ? "++" : "", type1); + } + + /* Called by the yacc grammar */ + void yyerror(s) + char *s; + { + (void) printf("%s\n",s); + Debug((stdout, "yychar=%d\n", yychar)); + } + + /* Called by the yacc grammar */ + int yywrap_nasko() + { + return 1; + } + + /* + * Support for dynamic strings: + * cat() creates a string from the concatenation + * of a null terminated list of input strings. + * The input strings are free()'d by cat() + * (so they better have been malloc()'d). + * + * the different methods of and + * are handled within these macros + */ + #if __STDC__ + # define VA_DCL(type,var) (type var,...) + # define VA_START(list,var,type) ((va_start(list,var)) , (var)) + #else + #if defined(DOS) + # define VA_DCL(type,var) (var,...) type var; + # define VA_START(list,var,type) ((va_start(list,var)) , (var)) + #else + #ifndef NOVARARGS + # define VA_DCL(type,var) (va_alist) va_dcl + # define VA_START(list,var,type) ((va_start(list)) , va_arg(list,type)) + #else + /* + * it is assumed here that machines which don't have either + * or will put its arguments on + * the stack in the "usual" way and consequently can grab + * the arguments using the "take the address of the first + * parameter and increment by sizeof" trick. + */ + # define VA_DCL(type,var) (var) type var; + # define VA_START(list,var,type) (list = (va_list)&(var) , (var)) + # define va_arg(list,type) ((type *)(list += sizeof(type)))[-1] + # define va_end(p) /* nothing */ + typedef char *va_list; + #endif /* NOVARARGS */ + #endif /* DOS */ + #endif /* __STDC__ */ + + /* VARARGS */ + char *cat + VA_DCL(char*, s1) + { + register char *newstr; + register unsigned len = 1; + char *str; + va_list args; + + /* find the length which needs to be allocated */ + str = VA_START(args, s1, char*); + for ( ; str; str = va_arg(args, char*)) + len += strlen(str); + va_end(args); + + /* allocate it */ + newstr = malloc(len); + if (newstr == 0) + { + (void) fprintf (stderr, "%s: out of malloc space within cat()!\n", + progname); + exit(1); + } + newstr[0] = '\0'; + + /* copy in the strings */ + str = VA_START(args, s1, char*); + for ( ; str; str = va_arg(args, char*)) + { + (void) strcat(newstr,str); + free(str); + } + va_end(args); + + Debug((stderr, "\tcat created '%s'\n", newstr)); + return newstr; + } + + /* + * ds() makes a malloc()'d string from one that's not. + */ + char *ds(s) + char *s; + { + register char *p = malloc((unsigned)(strlen(s)+1)); + + if (p) + (void) strcpy(p,s); + else + { + (void) fprintf (stderr, "%s: malloc() failed!\n", progname); + exit(1); + } + return p; + } + + /* return a visible representation of a character */ + char *visible(c) + int c; + { + static char buf[5]; + + c &= 0377; + if (isprint(c)) + { + buf[0] = c; + buf[1] = '\0'; + } + else + (void) sprintf(buf,"\\%03o",c); + return buf; + } + + #ifdef NOTMPFILE + /* provide a conservative version of tmpfile() */ + /* for those systems without it. */ + /* tmpfile() returns a FILE* of a file opened */ + /* for read&write. It is supposed to be */ + /* automatically removed when it gets closed, */ + /* but here we provide a separate rmtmpfile() */ + /* function to perform that function. */ + /* Also provide several possible file names to */ + /* try for opening. */ + static char *file4tmpfile = 0; + + FILE *tmpfile() + { + static char *listtmpfiles[] = + { + "/usr/tmp/cdeclXXXXXX", + "/tmp/cdeclXXXXXX", + "/cdeclXXXXXX", + "cdeclXXXXXX", + 0 + }; + + char **listp = listtmpfiles; + for ( ; *listp; listp++) + { + FILE *retfp; + (void) mktemp(*listp); + retfp = fopen(*listp, "w+"); + if (!retfp) + continue; + file4tmpfile = *listp; + return retfp; + } + + return 0; + } + + void rmtmpfile() + { + if (file4tmpfile) + (void) unlink(file4tmpfile); + } + #else + /* provide a mock rmtmpfile() for normal systems */ + # define rmtmpfile() /* nothing */ + #endif /* NOTMPFILE */ + + #ifndef NOGETOPT + extern int optind; + #else + /* This is a miniature version of getopt() which will */ + /* do just barely enough for us to get by below. */ + /* Options are not allowed to be bunched up together. */ + /* Option arguments are not supported. */ + int optind = 1; + + int getopt(argc,argv,optstring) + char **argv; + char *optstring; + { + int ret; + char *p; + + if ((argv[optind][0] != '-') + #ifdef DOS + && (argv[optind][0] != '/') + #endif /* DOS */ + ) + return EOF; + + ret = argv[optind][1]; + optind++; + + for (p = optstring; *p; p++) + if (*p == ret) + return ret; + + (void) fprintf (stderr, "%s: illegal option -- %s\n", + progname, visible(ret)); + + return '?'; + } + #endif + + /* the help messages */ + struct helpstruct + { + char *text; /* generic text */ + char *cpptext; /* C++ specific text */ + } helptext[] = + { /* up-to 23 lines of help text so it fits on (24x80) screens */ + /* 1 */{ "[] means optional; {} means 1 or more; <> means defined elsewhere", 0 }, + /* 2 */{ " commands are separated by ';' and newlines", 0 }, + /* 3 */{ "command:", 0 }, + /* 4 */{ " declare as ", 0 }, + /* 5 */{ " cast into ", 0 }, + /* 6 */{ " explain ", 0 }, + /* 7 */{ " set or set options", 0 }, + /* 8 */{ " help, ?", 0 }, + /* 9 */{ " quit or exit", 0 }, + /* 10 */{ "english:", 0 }, + /* 11 */{ " function [( )] returning ", 0 }, + /* 12 */{ " array [] of ", 0 }, + /* 13 */{ " [{ const | volatile | noalias }] pointer to ", + " [{const|volatile}] {pointer|reference} to [member of class ] " }, + /* 14 */{ " ", 0 }, + /* 15 */{ "type:", 0 }, + /* 16 */{ " {[] [{}] []}", 0 }, + /* 17 */{ " { struct | union | enum } ", + " {struct|class|union|enum} " }, + /* 18 */{ "decllist: a comma separated list of , or as ", 0 }, + /* 19 */{ "name: a C identifier", 0 }, + /* 20 */{ "gibberish: a C declaration, like 'int *x', or cast, like '(int *)x'", 0 }, + /* 21 */{ "storage-class: extern, static, auto, register", 0 }, + /* 22 */{ "C-type: int, char, float, double, or void", 0 }, + /* 23 */{ "modifier: short, long, signed, unsigned, const, volatile, or noalias", + "modifier: short, long, signed, unsigned, const, or volatile" }, + { 0, 0 } + }; + + /* Print out the help text */ + void dohelp() + { + register struct helpstruct *p; + register char *fmt = CplusplusFlag ? " %s\n" : "\t%s\n"; + + for (p = helptext; p->text; p++) + if (CplusplusFlag && p->cpptext) + (void) printf(fmt, p->cpptext); + else + (void) printf(fmt, p->text); + } + + /* Tell how to invoke cdecl. */ + void usage() + { + (void) fprintf (stderr, "Usage: %s [-r|-p|-a|-+] [-ci%s%s] [files...]\n", + progname, + #ifdef dodebug + "d", + #else + "", + #endif /* dodebug */ + #ifdef doyydebug + "D" + #else + "" + #endif /* doyydebug */ + ); + (void) fprintf (stderr, "\t-r Check against Ritchie PDP C Compiler\n"); + (void) fprintf (stderr, "\t-p Check against Pre-ANSI C Compiler\n"); + (void) fprintf (stderr, "\t-a Check against ANSI C Compiler%s\n", + CplusplusFlag ? "" : " (the default)"); + (void) fprintf (stderr, "\t-+ Check against C++ Compiler%s\n", + CplusplusFlag ? " (the default)" : ""); + (void) fprintf (stderr, "\t-c Create compilable output (include ; and {})\n"); + (void) fprintf (stderr, "\t-i Force interactive mode\n"); + #ifdef dodebug + (void) fprintf (stderr, "\t-d Turn on debugging mode\n"); + #endif /* dodebug */ + #ifdef doyydebug + (void) fprintf (stderr, "\t-D Turn on YACC debugging mode\n"); + #endif /* doyydebug */ + exit(1); + /* NOTREACHED */ + } + + /* Manage the prompts. */ + static int prompting = 1; + + void doprompt() { prompting = 1; } + void noprompt() { prompting = 0; } + + void prompt() + { + if ((OnATty || Interactive) && prompting) { + (void) printf("%s> ", progname); + (void) fflush(stdout); + } + } + + /* Save away the name of the program from argv[0] */ + void setprogname(argv0) + char *argv0; + { + #ifdef DOS + char *dot; + #endif /* DOS */ + + progname = strrchr(argv0, '/'); + + #ifdef DOS + if (!progname) + progname = strrchr(argv0, '\\'); + #endif /* DOS */ + + if (progname) + progname++; + else + progname = argv0; + + #ifdef DOS + dot = strchr(progname, '.'); + if (dot) + *dot = '\0'; + for (dot = progname; *dot; dot++) + *dot = tolower(*dot); + #endif /* DOS */ + } + + /* Run down the list of keywords to see if the */ + /* program is being called named as one of them */ + /* or the first argument is one of them. */ + int namedkeyword(argn) + char *argn; + { + static char *cmdlist[] = + { + "explain", "declare", "cast", "help", "?", "set", 0 + }; + + /* first check the program name */ + char **cmdptr = cmdlist; + for ( ; *cmdptr; cmdptr++) + if (strcmp(*cmdptr, progname) == 0) + { + KeywordName = 1; + return 1; + } + + /* now check $1 */ + for (cmdptr = cmdlist; *cmdptr; cmdptr++) + if (strcmp(*cmdptr, argn) == 0) + return 1; + + /* nope, must be file name arguments */ + return 0; + } + + /* Read from standard input, turning */ + /* on prompting if necessary. */ + int dostdin() + { + int ret; + OnATty = isatty(0); + if (OnATty || Interactive) + { + (void) printf("Type `help' or `?' for help\n"); + prompt(); + } + + yyin = stdin; + ret = yyparse(); + OnATty = 0; + return ret; + } + + /* Write the arguments into a file */ + /* and treat that file as the input. */ + int dotmpfile(argc, argv) + int argc; + char **argv; + { + int ret = 0; + FILE *tmpfp = tmpfile(); + if (!tmpfp) + { + int sverrno = errno; + (void) fprintf (stderr, "%s: cannot open temp file\n", + progname); + errno = sverrno; + perror(progname); + return 1; + } + + if (KeywordName) + if (fputs(progname, tmpfp) == EOF) + { + int sverrno; + errwrite: + sverrno = errno; + (void) fprintf (stderr, "%s: error writing to temp file\n", + progname); + errno = sverrno; + perror(progname); + (void) fclose(tmpfp); + rmtmpfile(); + return 1; + } + + for ( ; optind < argc; optind++) + if (fprintf(tmpfp, " %s", argv[optind]) == EOF) + goto errwrite; + + if (putc('\n', tmpfp) == EOF) + goto errwrite; + + rewind(tmpfp); + yyin = tmpfp; + ret += yyparse(); + (void) fclose(tmpfp); + rmtmpfile(); + + return ret; + } + + /* Read each of the named files for input. */ + int dofileargs(argc, argv) + int argc; + char **argv; + { + FILE *ifp; + int ret = 0; + + for ( ; optind < argc; optind++) + if (strcmp(argv[optind], "-") == 0) + ret += dostdin(); + + else if ((ifp = fopen(argv[optind], "r")) == NULL) + { + int sverrno = errno; + (void) fprintf (stderr, "%s: cannot open %s\n", + progname, argv[optind]); + errno = sverrno; + perror(argv[optind]); + ret++; + } + + else + { + yyin = ifp; + ret += yyparse(); + } + + return ret; + } + + /* print out a cast */ + void docast(name, left, right, type) + char *name, *left, *right, *type; + { + int lenl = strlen(left), lenr = strlen(right); + + if (prev == 'f') + unsupp("Cast into function", + "cast into pointer to function"); + else if (prev=='A' || prev=='a') + unsupp("Cast into array","cast into pointer"); + (void) printf("(%s%*s%s)%s\n", + type, lenl+lenr?lenl+1:0, + left, right, name ? name : "expression"); + free(left); + free(right); + free(type); + if (name) + free(name); + } + + /* print out a declaration */ + void dodeclare(name, storage, left, right, type) + char *name, *storage, *left, *right, *type; + { + if (prev == 'v') + unsupp("Variable of type void", + "variable of type pointer to void"); + + if (*storage == 'r') + switch (prev) + { + case 'f': unsupp("Register function", NullCP); break; + case 'A': + case 'a': unsupp("Register array", NullCP); break; + case 's': unsupp("Register struct/class", NullCP); break; + } + + if (*storage) + (void) printf("%s ", storage); + (void) printf("%s %s%s%s", + type, left, + name ? name : (prev == 'f') ? "f" : "var", right); + if (MkProgramFlag) { + if ((prev == 'f') && (*storage != 'e')) + (void) printf(" { }\n"); + else + (void) printf(";\n"); + } else { + (void) printf("\n"); + } + free(storage); + free(left); + free(right); + free(type); + if (name) + free(name); + } + + void dodexplain(storage, constvol, type, decl) + char *storage, *constvol, *type, *decl; + { + if (type && (strcmp(type, "void") == 0)) + if (prev == 'n') + unsupp("Variable of type void", + "variable of type pointer to void"); + else if (prev == 'a') + unsupp("array of type void", + "array of type pointer to void"); + else if (prev == 'r') + unsupp("reference to type void", + "pointer to void"); + + if (*storage == 'r') + switch (prev) + { + case 'f': unsupp("Register function", NullCP); break; + case 'A': + case 'a': unsupp("Register array", NullCP); break; + case 's': unsupp("Register struct/union/enum/class", NullCP); break; + } + + (void) printf("declare %s as ", savedname); + if (*storage) + (void) printf("%s ", storage); + (void) printf("%s", decl); + if (*constvol) + (void) printf("%s ", constvol); + (void) printf("%s\n", type ? type : "int"); + } + + void docexplain(constvol, type, cast, name) + char *constvol, *type, *cast, *name; + { + if (strcmp(type, "void") == 0) + if (prev == 'a') + unsupp("array of type void", + "array of type pointer to void"); + else if (prev == 'r') + unsupp("reference to type void", + "pointer to void"); + (void) printf("cast %s into %s", name, cast); + if (strlen(constvol) > 0) + (void) printf("%s ", constvol); + (void) printf("%s\n",type); + } + + /* Do the appropriate things for the "set" command. */ + void doset(opt) + char *opt; + { + if (strcmp(opt, "create") == 0) + { MkProgramFlag = 1; } + else if (strcmp(opt, "nocreate") == 0) + { MkProgramFlag = 0; } + else if (strcmp(opt, "interactive") == 0) + { Interactive = 1; } + else if (strcmp(opt, "nointeractive") == 0) + { Interactive = 0; OnATty = 0; } + else if (strcmp(opt, "ritchie") == 0) + { CplusplusFlag=0; RitchieFlag=1; PreANSIFlag=0; } + else if (strcmp(opt, "preansi") == 0) + { CplusplusFlag=0; RitchieFlag=0; PreANSIFlag=1; } + else if (strcmp(opt, "ansi") == 0) + { CplusplusFlag=0; RitchieFlag=0; PreANSIFlag=0; } + else if (strcmp(opt, "cplusplus") == 0) + { CplusplusFlag=1; RitchieFlag=0; PreANSIFlag=0; } + #ifdef dodebug + else if (strcmp(opt, "debug") == 0) + { DebugFlag = 1; } + else if (strcmp(opt, "nodebug") == 0) + { DebugFlag = 0; } + #endif /* dodebug */ + #ifdef doyydebug + else if (strcmp(opt, "yydebug") == 0) + { yydebug = 1; } + else if (strcmp(opt, "noyydebug") == 0) + { yydebug = 0; } + #endif /* doyydebug */ + else + { + if ((strcmp(opt, unknown_name) != 0) && + (strcmp(opt, "options") != 0)) + (void) printf("Unknown set option: '%s'\n", opt); + + (void) printf("Valid set options (and command line equivalents) are:\n"); + (void) printf("\toptions\n"); + (void) printf("\tcreate (-c), nocreate\n"); + (void) printf("\tinteractive (-i), nointeractive\n"); + (void) printf("\tritchie (-r), preansi (-p), ansi (-a) or cplusplus (-+)\n"); + #ifdef dodebug + (void) printf("\tdebug (-d), nodebug\n"); + #endif /* dodebug */ + #ifdef doyydebug + (void) printf("\tyydebug (-D), noyydebug\n"); + #endif /* doyydebug */ + + (void) printf("\nCurrent set values are:\n"); + (void) printf("\t%screate\n", MkProgramFlag ? " " : " no"); + (void) printf("\t%sinteractive\n", + (OnATty || Interactive) ? " " : " no"); + if (RitchieFlag) + (void) printf("\t ritchie\n"); + else + (void) printf("\t(noritchie)\n"); + if (PreANSIFlag) + (void) printf("\t preansi\n"); + else + (void) printf("\t(nopreansi)\n"); + if (!RitchieFlag && !PreANSIFlag && !CplusplusFlag) + (void) printf("\t ansi\n"); + else + (void) printf("\t(noansi)\n"); + if (CplusplusFlag) + (void) printf("\t cplusplus\n"); + else + (void) printf("\t(nocplusplus)\n"); + #ifdef dodebug + (void) printf("\t%sdebug\n", DebugFlag ? " " : " no"); + #endif /* dodebug */ + #ifdef doyydebug + (void) printf("\t%syydebug\n", yydebug ? " " : " no"); + #endif /* doyydebug */ + } + } + + void versions() + { + (void) printf("Version:\n\t%s\n\t%s\n\t%s\n", + cdeclsccsid, cdgramsccsid, cdlexsccsid); + exit(0); + } + + int main(int argc, char **argv) + { + int c, ret = 0; + + setprogname(argv[0]); + #ifdef DOS + if (strcmp(progname, "cppdecl") == 0) + #else + if (strcmp(progname, "c++decl") == 0) + #endif /* DOS */ + CplusplusFlag = 1; + + while ((c = getopt(argc, argv, "cirpa+dDV")) != EOF) + switch (c) + { + case 'c': MkProgramFlag=1; break; + case 'i': Interactive=1; break; + + /* The following are mutually exclusive. */ + /* Only the last one set prevails. */ + case 'r': CplusplusFlag=0; RitchieFlag=1; PreANSIFlag=0; break; + case 'p': CplusplusFlag=0; RitchieFlag=0; PreANSIFlag=1; break; + case 'a': CplusplusFlag=0; RitchieFlag=0; PreANSIFlag=0; break; + case '+': CplusplusFlag=1; RitchieFlag=0; PreANSIFlag=0; break; + + #ifdef dodebug + case 'd': DebugFlag=1; break; + #endif /* dodebug */ + #ifdef doyydebug + case 'D': yydebug=1; break; + #endif /* doyydebug */ + case 'V': versions(); break; + case '?': usage(); break; + } + + /* Run down the list of arguments, parsing each one. */ + + /* Use standard input if no file names or "-" is found. */ + if (optind == argc) + ret += dostdin(); + + /* If called as explain, declare or cast, or first */ + /* argument is one of those, use the command line */ + /* as the input. */ + else if (namedkeyword(argv[optind])) + ret += dotmpfile(argc, argv); + + else + ret += dofileargs(argc, argv); + + return ret; + /* NOTREACHED */ + } + + + + + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdgram.c.source diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdgram.c.source:1.1 *** /dev/null Tue Oct 5 14:08:39 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdgram.c.source Tue Oct 5 14:08:26 2004 *************** *** 0 **** --- 1,1157 ---- + # line 2 "cdgram.y" + /* Yacc grammar for ANSI and C++ cdecl. */ + /* The output of this file is included */ + /* into the C file cdecl.c. */ + char cdgramsccsid[] = "@(#)cdgram.y 2.2 3/30/88"; + + extern char prev; + + # line 8 "cdgram.y" + typedef union { + char *dynstr; + struct { + char *left; + char *right; + char *type; + } halves; + } YYSTYPE; + # define ARRAY 257 + # define AS 258 + # define CAST 259 + # define COMMA 260 + # define DECLARE 261 + # define DOUBLECOLON 262 + # define EXPLAIN 263 + # define FUNCTION 264 + # define HELP 265 + # define INTO 266 + # define OF 267 + # define MEMBER 268 + # define POINTER 269 + # define REFERENCE 270 + # define RETURNING 271 + # define SET 272 + # define TO 273 + # define CHAR 274 + # define CLASS 275 + # define CONSTVOLATILE 276 + # define DOUBLE 277 + # define ENUM 278 + # define FLOAT 279 + # define INT 280 + # define LONG 281 + # define NAME 282 + # define NUMBER 283 + # define SHORT 284 + # define SIGNED 285 + # define STRUCT 286 + # define UNION 287 + # define UNSIGNED 288 + # define VOID 289 + # define AUTO 290 + # define EXTERN 291 + # define REGISTER 292 + # define STATIC 293 + #define yyclearin yychar = -1 + #define yyerrok yyerrflag = 0 + extern int yychar; + extern short yyerrflag; + #ifndef YYMAXDEPTH + #define YYMAXDEPTH 150 + #endif + YYSTYPE yylval, yyval; + # define YYERRCODE 256 + + # line 855 "cdgram.y" + + short yyexca[] ={ + -1, 1, + 0, -1, + -2, 0, + -1, 27, + 282, 81, + 40, 81, + 42, 81, + 38, 81, + -2, 87, + -1, 37, + 260, 31, + 41, 31, + -2, 81, + -1, 87, + 282, 82, + 40, 82, + 42, 82, + 38, 82, + -2, 80, + -1, 92, + 260, 31, + 41, 31, + -2, 81, + }; + # define YYNPROD 89 + # define YYLAST 322 + short yyact[]={ + + 67, 79, 28, 69, 72, 68, 66, 76, 159, 13, + 77, 75, 78, 73, 74, 70, 79, 16, 17, 18, + 19, 16, 17, 18, 19, 67, 129, 78, 69, 103, + 68, 66, 125, 25, 76, 39, 23, 77, 75, 128, + 70, 74, 118, 22, 115, 137, 117, 118, 85, 115, + 86, 117, 83, 23, 152, 25, 30, 100, 23, 10, + 22, 56, 25, 23, 47, 22, 60, 59, 37, 97, + 22, 121, 25, 40, 41, 123, 58, 25, 20, 34, + 139, 110, 25, 161, 144, 93, 145, 92, 94, 32, + 24, 57, 147, 71, 126, 29, 81, 21, 42, 55, + 8, 136, 108, 150, 12, 135, 33, 106, 11, 114, + 31, 10, 62, 151, 132, 134, 44, 45, 48, 49, + 156, 43, 35, 2, 63, 15, 53, 1, 54, 14, + 50, 64, 27, 65, 52, 101, 26, 46, 87, 82, + 61, 38, 0, 90, 80, 88, 0, 0, 89, 0, + 95, 96, 98, 108, 91, 108, 0, 0, 108, 0, + 11, 0, 51, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 109, 0, 111, 104, 102, 0, + 0, 0, 105, 112, 107, 0, 122, 99, 0, 113, + 0, 119, 120, 0, 0, 0, 0, 127, 0, 0, + 0, 0, 0, 0, 0, 124, 131, 0, 133, 0, + 0, 0, 0, 142, 0, 0, 130, 143, 0, 0, + 0, 0, 0, 0, 0, 138, 146, 140, 141, 148, + 0, 149, 0, 0, 0, 0, 127, 0, 0, 0, + 153, 0, 0, 25, 158, 0, 0, 127, 0, 128, + 155, 160, 16, 17, 18, 19, 154, 0, 0, 0, + 0, 157, 0, 0, 0, 0, 0, 25, 0, 0, + 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 116, 0, 0, 0, + 0, 116, 84, 0, 0, 0, 0, 0, 0, 36, + 0, 0, 145, 145, 92, 9, 0, 0, 5, 0, + 4, 0, 6, 0, 3, 0, 0, 0, 0, 0, + 0, 7 }; + short yypact[]={ + + -1000, 49,-1000, 101,-273,-204, -38,-226,-1000, 101, + -1000,-1000,-1000,-169,-194,-1000,-1000,-1000,-1000,-1000, + -187, 101, 28,-248,-196,-214,-212,-214,-214, 101, + -1000,-1000,-269, 101,-194,-1000,-194,-221,-191,-1000, + -206,-207,-1000,-274,-1000,-1000, 10,-214, 10,-1000, + -1000,-194,-1000, 101,-1000, 44,-170,-1000,-194,-199, + -194,-1000,-249,-1000,-225,-247,-1000,-1000,-1000,-1000, + -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, + 10, 101, 67,-214,-181,-214, 10,-1000, 101, 9, + 101,-1000,-221,-200,-194,-1000,-1000,-192,-1000,-1000, + -1000,-1000,-1000,-1000, 101,-1000, -9,-1000, -67, 10, + 72, 10, 74,-1000, 64, 4,-182, 9, 9,-1000, + -173,-194,-1000,-259,-1000,-1000, 43,-1000,-1000,-1000, + -1,-1000, 10,-1000,-1000,-226,-1000,-1000, 62, 71, + 11, 11,-1000,-228,-1000,-243, 9,-1000,-1000, 101, + 80, 9,-194,-174, 11,-1000, -33, 11,-1000,-1000, + 42,-1000 }; + short yypgo[]={ + + 0, 99, 141, 140, 109, 94, 96, 139, 101, 137, + 93, 112, 135, 133, 90, 95, 129, 125, 131, 124, + 98, 91, 127, 123, 100, 121 }; + short yyr1[]={ + + 0, 22, 22, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 24, 24, 15, 15, 6, + 6, 6, 6, 7, 7, 7, 7, 7, 5, 5, + 5, 1, 1, 1, 1, 1, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 8, 8, 21, 21, 21, + 21, 21, 21, 21, 2, 2, 20, 25, 3, 3, + 3, 3, 18, 18, 18, 10, 10, 19, 19, 19, + 19, 19, 11, 11, 12, 12, 13, 13, 13, 13, + 14, 14, 9, 17, 17, 17, 17, 16, 16 }; + short yyr2[]={ + + 0, 0, 2, 2, 6, 4, 5, 3, 6, 5, + 5, 8, 3, 1, 2, 1, 1, 1, 0, 1, + 3, 4, 3, 3, 4, 2, 3, 1, 3, 3, + 1, 0, 3, 1, 1, 3, 0, 2, 5, 6, + 3, 4, 2, 2, 2, 2, 3, 3, 6, 4, + 4, 8, 4, 2, 0, 1, 2, 0, 1, 1, + 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, + 2, 0, 2, 1, 1, 1, 1, 1, 0 }; + short yychk[]={ + + -1000, -22, -23, 265, 261, 259, 263, 272, -24, 256, + 10, 59, -24, 282, -16, -17, 290, 291, 292, 293, + 282, -21, 264, 257, -14, 276, -16, -17, 40, -15, + 282, -24, 258, -21, 266, -24, 271, 40, -2, 283, + 269, 270, -20, -25, -14, -14, -9, 276, -14, -14, + -24, -16, -24, -21, -21, -1, 282, -21, 267, 273, + 273, -3, -11, -19, -18, -13, 280, 274, 279, 277, + 289, -10, 278, 287, 288, 285, 281, 284, 286, 275, + -20, -6, -7, 42, 282, 38, 40, -14, -6, -20, + -21, -24, 260, 41, 258, -21, -21, 268, -21, -19, + 282, -12, -11, 276, -6, -24, 40, -8, 91, -14, + 262, -14, -6, -24, -4, 40, 282, 42, 38, -24, + -1, 271, -21, 267, -24, 41, -5, -14, 282, 93, + 283, -6, 42, -6, 41, 41, -8, 41, -4, 262, + -4, -4, -21, -10, 41, 260, -20, 93, -6, -15, + 41, 42, 282, -5, -4, -24, 40, -4, -21, 41, + -5, 41 }; + short yydef[]={ + + 1, -2, 2, 0, 88, 81, 88, 18, 13, 0, + 15, 16, 3, 0, 81, 87, 83, 84, 85, 86, + 0, 0, 0, 54, 57, 81, 81, -2, 81, 0, + 17, 14, 88, 0, 81, 7, 81, -2, 0, 55, + 0, 0, 53, 0, 80, 57, 0, 81, 0, 57, + 12, 81, 5, 0, 47, 0, 33, 34, 81, 81, + 81, 56, 58, 59, 0, 73, 67, 68, 69, 70, + 71, 62, 63, 64, 76, 77, 78, 79, 65, 66, + 0, 0, 19, 81, 27, 81, 0, -2, 0, 36, + 0, 6, -2, 0, 81, 49, 50, 0, 52, 60, + 61, 72, 74, 75, 0, 10, 81, 25, 0, 0, + 0, 0, 0, 9, 0, 36, 0, 36, 36, 4, + 32, 81, 35, 0, 8, 23, 0, 57, 30, 45, + 0, 20, 0, 22, 26, 18, 44, 37, 0, 0, + 42, 43, 48, 0, 24, 81, 36, 46, 21, 0, + 40, 36, 81, 28, 29, 11, 81, 41, 51, 38, + 0, 39 }; + #ifndef lint + static char yaccpar_sccsid[] = "@(#)yaccpar 1.6 88/02/08 SMI"; /* from UCB 4.1 83/02/11 */ + #endif + + # + # define YYFLAG -1000 + # define YYERROR goto yyerrlab + # define YYACCEPT return(0) + # define YYABORT return(1) + + /* parser for yacc output */ + + #ifdef YYDEBUG + int yydebug = 0; /* 1 for debugging */ + #endif + YYSTYPE yyv[YYMAXDEPTH]; /* where the values are stored */ + int yychar = -1; /* current input token number */ + int yynerrs = 0; /* number of errors */ + short yyerrflag = 0; /* error recovery flag */ + + yyparse() { + + short yys[YYMAXDEPTH]; + short yyj, yym; + register YYSTYPE *yypvt; + register short yystate, *yyps, yyn; + register YYSTYPE *yypv; + register short *yyxi; + + yystate = 0; + yychar = -1; + yynerrs = 0; + yyerrflag = 0; + yyps= &yys[-1]; + yypv= &yyv[-1]; + + yystack: /* put a state and value onto the stack */ + + #ifdef YYDEBUG + if( yydebug ) printf( "state %d, char 0%o\n", yystate, yychar ); + #endif + if( ++yyps>= &yys[YYMAXDEPTH] ) { yyerror( "yacc stack overflow" ); return(1); } + *yyps = yystate; + ++yypv; + *yypv = yyval; + + yynewstate: + + yyn = yypact[yystate]; + + if( yyn<= YYFLAG ) goto yydefault; /* simple state */ + + if( yychar<0 ) if( (yychar=yylex())<0 ) yychar=0; + if( (yyn += yychar)<0 || yyn >= YYLAST ) goto yydefault; + + if( yychk[ yyn=yyact[ yyn ] ] == yychar ){ /* valid shift */ + yychar = -1; + yyval = yylval; + yystate = yyn; + if( yyerrflag > 0 ) --yyerrflag; + goto yystack; + } + + yydefault: + /* default state action */ + + if( (yyn=yydef[yystate]) == -2 ) { + if( yychar<0 ) if( (yychar=yylex())<0 ) yychar = 0; + /* look through exception table */ + + for( yyxi=yyexca; (*yyxi!= (-1)) || (yyxi[1]!=yystate) ; yyxi += 2 ) ; /* VOID */ + + while( *(yyxi+=2) >= 0 ){ + if( *yyxi == yychar ) break; + } + if( (yyn = yyxi[1]) < 0 ) return(0); /* accept */ + } + + if( yyn == 0 ){ /* error */ + /* error ... attempt to resume parsing */ + + switch( yyerrflag ){ + + case 0: /* brand new error */ + + yyerror( "syntax error" ); + yyerrlab: + ++yynerrs; + + case 1: + case 2: /* incompletely recovered error ... try again */ + + yyerrflag = 3; + + /* find a state where "error" is a legal shift action */ + + while ( yyps >= yys ) { + yyn = yypact[*yyps] + YYERRCODE; + if( yyn>= 0 && yyn < YYLAST && yychk[yyact[yyn]] == YYERRCODE ){ + yystate = yyact[yyn]; /* simulate a shift of "error" */ + goto yystack; + } + yyn = yypact[*yyps]; + + /* the current yyps has no shift onn "error", pop stack */ + + #ifdef YYDEBUG + if( yydebug ) printf( "error recovery pops state %d, uncovers %d\n", *yyps, yyps[-1] ); + #endif + --yyps; + --yypv; + } + + /* there is no state on the stack with an error shift ... abort */ + + yyabort: + return(1); + + + case 3: /* no shift yet; clobber input char */ + + #ifdef YYDEBUG + if( yydebug ) printf( "error recovery discards char %d\n", yychar ); + #endif + + if( yychar == 0 ) goto yyabort; /* don't discard EOF, quit */ + yychar = -1; + goto yynewstate; /* try again in the same state */ + + } + + } + + /* reduction by production yyn */ + + #ifdef YYDEBUG + if( yydebug ) printf("reduce %d\n",yyn); + #endif + yyps -= yyr2[yyn]; + yypvt = yypv; + yypv -= yyr2[yyn]; + yyval = yypv[1]; + yym=yyn; + /* consult goto table to find next state */ + yyn = yyr1[yyn]; + yyj = yypgo[yyn] + *yyps + 1; + if( yyj>=YYLAST || yychk[ yystate = yyact[yyj] ] != -yyn ) yystate = yyact[yypgo[yyn]]; + switch(yym){ + + case 2: + # line 33 "cdgram.y" + { + prompt(); + prev = 0; + } break; + case 3: + # line 40 "cdgram.y" + { + Debug((stderr, "stmt: help\n")); + dohelp(); + } break; + case 4: + # line 46 "cdgram.y" + { + Debug((stderr, "stmt: DECLARE NAME AS opt_storage adecl\n")); + Debug((stderr, "\tNAME='%s'\n", yypvt[-4].dynstr)); + Debug((stderr, "\topt_storage='%s'\n", yypvt[-2].dynstr)); + Debug((stderr, "\tacdecl.left='%s'\n", yypvt[-1].halves.left)); + Debug((stderr, "\tacdecl.right='%s'\n", yypvt[-1].halves.right)); + Debug((stderr, "\tacdecl.type='%s'\n", yypvt[-1].halves.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + dodeclare(yypvt[-4].dynstr, yypvt[-2].dynstr, yypvt[-1].halves.left, yypvt[-1].halves.right, yypvt[-1].halves.type); + } break; + case 5: + # line 58 "cdgram.y" + { + Debug((stderr, "stmt: DECLARE opt_storage adecl\n")); + Debug((stderr, "\topt_storage='%s'\n", yypvt[-2].dynstr)); + Debug((stderr, "\tacdecl.left='%s'\n", yypvt[-1].halves.left)); + Debug((stderr, "\tacdecl.right='%s'\n", yypvt[-1].halves.right)); + Debug((stderr, "\tacdecl.type='%s'\n", yypvt[-1].halves.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + dodeclare(NullCP, yypvt[-2].dynstr, yypvt[-1].halves.left, yypvt[-1].halves.right, yypvt[-1].halves.type); + } break; + case 6: + # line 69 "cdgram.y" + { + Debug((stderr, "stmt: CAST NAME AS adecl\n")); + Debug((stderr, "\tNAME='%s'\n", yypvt[-3].dynstr)); + Debug((stderr, "\tacdecl.left='%s'\n", yypvt[-1].halves.left)); + Debug((stderr, "\tacdecl.right='%s'\n", yypvt[-1].halves.right)); + Debug((stderr, "\tacdecl.type='%s'\n", yypvt[-1].halves.type)); + docast(yypvt[-3].dynstr, yypvt[-1].halves.left, yypvt[-1].halves.right, yypvt[-1].halves.type); + } break; + case 7: + # line 79 "cdgram.y" + { + Debug((stderr, "stmt: CAST adecl\n")); + Debug((stderr, "\tacdecl.left='%s'\n", yypvt[-1].halves.left)); + Debug((stderr, "\tacdecl.right='%s'\n", yypvt[-1].halves.right)); + Debug((stderr, "\tacdecl.type='%s'\n", yypvt[-1].halves.type)); + docast(NullCP, yypvt[-1].halves.left, yypvt[-1].halves.right, yypvt[-1].halves.type); + } break; + case 8: + # line 88 "cdgram.y" + { + Debug((stderr, "stmt: EXPLAIN opt_storage opt_constvol_list type cdecl\n")); + Debug((stderr, "\topt_storage='%s'\n", yypvt[-4].dynstr)); + Debug((stderr, "\topt_constvol_list='%s'\n", yypvt[-3].dynstr)); + Debug((stderr, "\ttype='%s'\n", yypvt[-2].dynstr)); + Debug((stderr, "\tcdecl='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + dodexplain(yypvt[-4].dynstr, yypvt[-3].dynstr, yypvt[-2].dynstr, yypvt[-1].dynstr); + } break; + case 9: + # line 99 "cdgram.y" + { + Debug((stderr, "stmt: EXPLAIN storage opt_constvol_list cdecl\n")); + Debug((stderr, "\tstorage='%s'\n", yypvt[-3].dynstr)); + Debug((stderr, "\topt_constvol_list='%s'\n", yypvt[-2].dynstr)); + Debug((stderr, "\tcdecl='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + dodexplain(yypvt[-3].dynstr, yypvt[-2].dynstr, NullCP, yypvt[-1].dynstr); + } break; + case 10: + # line 109 "cdgram.y" + { + Debug((stderr, "stmt: EXPLAIN opt_storage constvol_list cdecl\n")); + Debug((stderr, "\topt_storage='%s'\n", yypvt[-3].dynstr)); + Debug((stderr, "\tconstvol_list='%s'\n", yypvt[-2].dynstr)); + Debug((stderr, "\tcdecl='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + dodexplain(yypvt[-3].dynstr, yypvt[-2].dynstr, NullCP, yypvt[-1].dynstr); + } break; + case 11: + # line 119 "cdgram.y" + { + Debug((stderr, "stmt: EXPLAIN ( opt_constvol_list type cast ) optNAME\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", yypvt[-5].dynstr)); + Debug((stderr, "\ttype='%s'\n", yypvt[-4].dynstr)); + Debug((stderr, "\tcast='%s'\n", yypvt[-3].dynstr)); + Debug((stderr, "\tNAME='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + docexplain(yypvt[-5].dynstr, yypvt[-4].dynstr, yypvt[-3].dynstr, yypvt[-1].dynstr); + } break; + case 12: + # line 130 "cdgram.y" + { + Debug((stderr, "stmt: SET optNAME\n")); + Debug((stderr, "\toptNAME='%s'\n", yypvt[-1].dynstr)); + doset(yypvt[-1].dynstr); + } break; + case 14: + # line 138 "cdgram.y" + { + yyerrok; + } break; + case 15: + # line 144 "cdgram.y" + { + doprompt(); + } break; + case 16: + # line 148 "cdgram.y" + { + noprompt(); + } break; + case 17: + # line 154 "cdgram.y" + { + Debug((stderr, "optNAME: NAME\n")); + Debug((stderr, "\tNAME='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = yypvt[-0].dynstr; + } break; + case 18: + # line 161 "cdgram.y" + { + Debug((stderr, "optNAME: EMPTY\n")); + yyval.dynstr = ds(unknown_name); + } break; + case 20: + # line 169 "cdgram.y" + { + Debug((stderr, "cdecl: * opt_constvol_list cdecl\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\tcdecl='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = cat(yypvt[-0].dynstr,yypvt[-1].dynstr,ds(strlen(yypvt[-1].dynstr)?" pointer to ":"pointer to "),NullCP); + prev = 'p'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 21: + # line 179 "cdgram.y" + { + Debug((stderr, "cdecl: NAME DOUBLECOLON '*' cdecl\n")); + Debug((stderr, "\tNAME='%s'\n", yypvt[-3].dynstr)); + Debug((stderr, "\tcdecl='%s'\n", yypvt[-0].dynstr)); + if (!CplusplusFlag) + unsupp("pointer to member of class", NullCP); + yyval.dynstr = cat(yypvt[-0].dynstr,ds("pointer to member of class "),yypvt[-3].dynstr,ds(" "),NullCP); + prev = 'p'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 22: + # line 191 "cdgram.y" + { + Debug((stderr, "cdecl: & opt_constvol_list cdecl\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\tcdecl='%s'\n", yypvt[-0].dynstr)); + if (!CplusplusFlag) + unsupp("reference", NullCP); + yyval.dynstr = cat(yypvt[-0].dynstr,yypvt[-1].dynstr,ds(strlen(yypvt[-1].dynstr)?" reference to ":"reference to "),NullCP); + prev = 'r'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 23: + # line 204 "cdgram.y" + { + Debug((stderr, "cdecl1: cdecl1()\n")); + Debug((stderr, "\tcdecl1='%s'\n", yypvt[-2].dynstr)); + yyval.dynstr = cat(yypvt[-2].dynstr,ds("function returning "),NullCP); + prev = 'f'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 24: + # line 213 "cdgram.y" + { + Debug((stderr, "cdecl1: cdecl1(castlist)\n")); + Debug((stderr, "\tcdecl1='%s'\n", yypvt[-3].dynstr)); + Debug((stderr, "\tcastlist='%s'\n", yypvt[-1].dynstr)); + yyval.dynstr = cat(yypvt[-3].dynstr, ds("function ("), + yypvt[-1].dynstr, ds(") returning "), NullCP); + prev = 'f'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 25: + # line 224 "cdgram.y" + { + Debug((stderr, "cdecl1: cdecl1 cdims\n")); + Debug((stderr, "\tcdecl1='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\tcdims='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = cat(yypvt[-1].dynstr,ds("array "),yypvt[-0].dynstr,NullCP); + prev = 'a'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 26: + # line 234 "cdgram.y" + { + Debug((stderr, "cdecl1: (cdecl)\n")); + Debug((stderr, "\tcdecl='%s'\n", yypvt[-1].dynstr)); + yyval.dynstr = yypvt[-1].dynstr; + /* prev = prev; */ + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 27: + # line 243 "cdgram.y" + { + Debug((stderr, "cdecl1: NAME\n")); + Debug((stderr, "\tNAME='%s'\n", yypvt[-0].dynstr)); + savedname = yypvt[-0].dynstr; + yyval.dynstr = ds(""); + prev = 'n'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 28: + # line 254 "cdgram.y" + { + Debug((stderr, "castlist: castlist1, castlist2\n")); + Debug((stderr, "\tcastlist1='%s'\n", yypvt[-2].dynstr)); + Debug((stderr, "\tcastlist2='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = cat(yypvt[-2].dynstr, ds(", "), yypvt[-0].dynstr, NullCP); + } break; + case 29: + # line 262 "cdgram.y" + { + Debug((stderr, "castlist: opt_constvol_list type cast\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", yypvt[-2].dynstr)); + Debug((stderr, "\ttype='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\tcast='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = cat(yypvt[-0].dynstr, yypvt[-2].dynstr, ds(strlen(yypvt[-2].dynstr) ? " " : ""), yypvt[-1].dynstr, NullCP); + } break; + case 30: + # line 271 "cdgram.y" + { + yyval.dynstr = yypvt[-0].dynstr; + } break; + case 31: + # line 277 "cdgram.y" + { + Debug((stderr, "adecllist: EMPTY\n")); + yyval.dynstr = ds(""); + } break; + case 32: + # line 283 "cdgram.y" + { + Debug((stderr, "adecllist: adecllist1, adecllist2\n")); + Debug((stderr, "\tadecllist1='%s'\n", yypvt[-2].dynstr)); + Debug((stderr, "\tadecllist2='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = cat(yypvt[-2].dynstr, ds(", "), yypvt[-0].dynstr, NullCP); + } break; + case 33: + # line 291 "cdgram.y" + { + Debug((stderr, "adecllist: NAME\n")); + Debug((stderr, "\tNAME='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = yypvt[-0].dynstr; + } break; + case 34: + # line 298 "cdgram.y" + { + Debug((stderr, "adecllist: adecl\n")); + Debug((stderr, "\tadecl.left='%s'\n", yypvt[-0].halves.left)); + Debug((stderr, "\tadecl.right='%s'\n", yypvt[-0].halves.right)); + Debug((stderr, "\tadecl.type='%s'\n", yypvt[-0].halves.type)); + yyval.dynstr = cat(yypvt[-0].halves.type, ds(" "), yypvt[-0].halves.left, yypvt[-0].halves.right, NullCP); + } break; + case 35: + # line 307 "cdgram.y" + { + Debug((stderr, "adecllist: NAME AS adecl\n")); + Debug((stderr, "\tNAME='%s'\n", yypvt[-2].dynstr)); + Debug((stderr, "\tadecl.left='%s'\n", yypvt[-0].halves.left)); + Debug((stderr, "\tadecl.right='%s'\n", yypvt[-0].halves.right)); + Debug((stderr, "\tadecl.type='%s'\n", yypvt[-0].halves.type)); + yyval.dynstr = cat(yypvt[-0].halves.type, ds(" "), yypvt[-0].halves.left, yypvt[-2].dynstr, yypvt[-0].halves.right, NullCP); + } break; + case 36: + # line 318 "cdgram.y" + { + Debug((stderr, "cast: EMPTY\n")); + yyval.dynstr = ds(""); + /* prev = prev; */ + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 37: + # line 326 "cdgram.y" + { + Debug((stderr, "cast: ()\n")); + yyval.dynstr = ds("function returning "); + prev = 'f'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 38: + # line 334 "cdgram.y" + { + Debug((stderr, "cast: (cast)()\n")); + Debug((stderr, "\tcast='%s'\n", yypvt[-3].dynstr)); + yyval.dynstr = cat(yypvt[-3].dynstr,ds("function returning "),NullCP); + prev = 'f'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 39: + # line 343 "cdgram.y" + { + Debug((stderr, "cast: (cast)(castlist)\n")); + Debug((stderr, "\tcast='%s'\n", yypvt[-4].dynstr)); + Debug((stderr, "\tcastlist='%s'\n", yypvt[-1].dynstr)); + yyval.dynstr = cat(yypvt[-4].dynstr,ds("function ("),yypvt[-1].dynstr,ds(") returning "),NullCP); + prev = 'f'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 40: + # line 353 "cdgram.y" + { + Debug((stderr, "cast: (cast)\n")); + Debug((stderr, "\tcast='%s'\n", yypvt[-1].dynstr)); + yyval.dynstr = yypvt[-1].dynstr; + /* prev = prev; */ + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 41: + # line 362 "cdgram.y" + { + Debug((stderr, "cast: NAME::*cast\n")); + Debug((stderr, "\tcast='%s'\n", yypvt[-0].dynstr)); + if (!CplusplusFlag) + unsupp("pointer to member of class", NullCP); + yyval.dynstr = cat(yypvt[-0].dynstr,ds("pointer to member of class "),yypvt[-3].dynstr,ds(" "),NullCP); + prev = 'p'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 42: + # line 373 "cdgram.y" + { + Debug((stderr, "cast: *cast\n")); + Debug((stderr, "\tcast='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = cat(yypvt[-0].dynstr,ds("pointer to "),NullCP); + prev = 'p'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 43: + # line 382 "cdgram.y" + { + Debug((stderr, "cast: &cast\n")); + Debug((stderr, "\tcast='%s'\n", yypvt[-0].dynstr)); + if (!CplusplusFlag) + unsupp("reference", NullCP); + yyval.dynstr = cat(yypvt[-0].dynstr,ds("reference to "),NullCP); + prev = 'r'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 44: + # line 393 "cdgram.y" + { + Debug((stderr, "cast: cast cdims\n")); + Debug((stderr, "\tcast='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\tcdims='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = cat(yypvt[-1].dynstr,ds("array "),yypvt[-0].dynstr,NullCP); + prev = 'a'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 45: + # line 404 "cdgram.y" + { + Debug((stderr, "cdims: []\n")); + yyval.dynstr = ds("of "); + } break; + case 46: + # line 410 "cdgram.y" + { + Debug((stderr, "cdims: [NUMBER]\n")); + Debug((stderr, "\tNUMBER='%s'\n", yypvt[-1].dynstr)); + yyval.dynstr = cat(yypvt[-1].dynstr,ds(" of "),NullCP); + } break; + case 47: + # line 418 "cdgram.y" + { + Debug((stderr, "adecl: FUNCTION RETURNING adecl\n")); + Debug((stderr, "\tadecl.left='%s'\n", yypvt[-0].halves.left)); + Debug((stderr, "\tadecl.right='%s'\n", yypvt[-0].halves.right)); + Debug((stderr, "\tadecl.type='%s'\n", yypvt[-0].halves.type)); + if (prev == 'f') + unsupp("Function returning function", + "function returning pointer to function"); + else if (prev=='A' || prev=='a') + unsupp("Function returning array", + "function returning pointer"); + yyval.halves.left = yypvt[-0].halves.left; + yyval.halves.right = cat(ds("()"),yypvt[-0].halves.right,NullCP); + yyval.halves.type = yypvt[-0].halves.type; + prev = 'f'; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", yyval.halves.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", yyval.halves.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", yyval.halves.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 48: + # line 441 "cdgram.y" + { + Debug((stderr, "adecl: FUNCTION (adecllist) RETURNING adecl\n")); + Debug((stderr, "\tadecllist='%s'\n", yypvt[-3].dynstr)); + Debug((stderr, "\tadecl.left='%s'\n", yypvt[-0].halves.left)); + Debug((stderr, "\tadecl.right='%s'\n", yypvt[-0].halves.right)); + Debug((stderr, "\tadecl.type='%s'\n", yypvt[-0].halves.type)); + if (prev == 'f') + unsupp("Function returning function", + "function returning pointer to function"); + else if (prev=='A' || prev=='a') + unsupp("Function returning array", + "function returning pointer"); + yyval.halves.left = yypvt[-0].halves.left; + yyval.halves.right = cat(ds("("),yypvt[-3].dynstr,ds(")"),yypvt[-0].halves.right,NullCP); + yyval.halves.type = yypvt[-0].halves.type; + prev = 'f'; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", yyval.halves.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", yyval.halves.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", yyval.halves.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 49: + # line 465 "cdgram.y" + { + Debug((stderr, "adecl: ARRAY adims OF adecl\n")); + Debug((stderr, "\tadims='%s'\n", yypvt[-2].dynstr)); + Debug((stderr, "\tadecl.left='%s'\n", yypvt[-0].halves.left)); + Debug((stderr, "\tadecl.right='%s'\n", yypvt[-0].halves.right)); + Debug((stderr, "\tadecl.type='%s'\n", yypvt[-0].halves.type)); + if (prev == 'f') + unsupp("Array of function", + "array of pointer to function"); + else if (prev == 'a') + unsupp("Inner array of unspecified size", + "array of pointer"); + else if (prev == 'v') + unsupp("Array of void", + "pointer to void"); + if (arbdims) + prev = 'a'; + else + prev = 'A'; + yyval.halves.left = yypvt[-0].halves.left; + yyval.halves.right = cat(yypvt[-2].dynstr,yypvt[-0].halves.right,NullCP); + yyval.halves.type = yypvt[-0].halves.type; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", yyval.halves.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", yyval.halves.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", yyval.halves.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 50: + # line 495 "cdgram.y" + { + char *op = "", *cp = "", *sp = ""; + + Debug((stderr, "adecl: opt_constvol_list POINTER TO adecl\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", yypvt[-3].dynstr)); + Debug((stderr, "\tadecl.left='%s'\n", yypvt[-0].halves.left)); + Debug((stderr, "\tadecl.right='%s'\n", yypvt[-0].halves.right)); + Debug((stderr, "\tadecl.type='%s'\n", yypvt[-0].halves.type)); + if (prev == 'a') + unsupp("Pointer to array of unspecified dimension", + "pointer to object"); + if (prev=='a' || prev=='A' || prev=='f') { + op = "("; + cp = ")"; + } + if (strlen(yypvt[-3].dynstr) != 0) + sp = " "; + yyval.halves.left = cat(yypvt[-0].halves.left,ds(op),ds("*"), + ds(sp),yypvt[-3].dynstr,ds(sp),NullCP); + yyval.halves.right = cat(ds(cp),yypvt[-0].halves.right,NullCP); + yyval.halves.type = yypvt[-0].halves.type; + prev = 'p'; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", yyval.halves.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", yyval.halves.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", yyval.halves.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 51: + # line 525 "cdgram.y" + { + char *op = "", *cp = "", *sp = ""; + + Debug((stderr, "adecl: opt_constvol_list POINTER TO MEMBER OF ClassStruct NAME adecl\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", yypvt[-7].dynstr)); + Debug((stderr, "\tClassStruct='%s'\n", yypvt[-2].dynstr)); + Debug((stderr, "\tNAME='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\tadecl.left='%s'\n", yypvt[-0].halves.left)); + Debug((stderr, "\tadecl.right='%s'\n", yypvt[-0].halves.right)); + Debug((stderr, "\tadecl.type='%s'\n", yypvt[-0].halves.type)); + if (!CplusplusFlag) + unsupp("pointer to member of class", NullCP); + if (prev == 'a') + unsupp("Pointer to array of unspecified dimension", + "pointer to object"); + if (prev=='a' || prev=='A' || prev=='f') { + op = "("; + cp = ")"; + } + if (strlen(yypvt[-7].dynstr) != 0) + sp = " "; + yyval.halves.left = cat(yypvt[-0].halves.left,ds(op),yypvt[-1].dynstr,ds("::*"), + ds(sp),yypvt[-7].dynstr,ds(sp),NullCP); + yyval.halves.right = cat(ds(cp),yypvt[-0].halves.right,NullCP); + yyval.halves.type = yypvt[-0].halves.type; + prev = 'p'; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", yyval.halves.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", yyval.halves.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", yyval.halves.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 52: + # line 559 "cdgram.y" + { + char *op = "", *cp = "", *sp = ""; + + Debug((stderr, "adecl: opt_constvol_list REFERENCE TO adecl\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", yypvt[-3].dynstr)); + Debug((stderr, "\tadecl.left='%s'\n", yypvt[-0].halves.left)); + Debug((stderr, "\tadecl.right='%s'\n", yypvt[-0].halves.right)); + Debug((stderr, "\tadecl.type='%s'\n", yypvt[-0].halves.type)); + if (!CplusplusFlag) + unsupp("reference", NullCP); + if (prev == 'v') + unsupp("Reference to void", + "pointer to void"); + else if (prev == 'a') + unsupp("Reference to array of unspecified dimension", + "reference to object"); + if (prev=='a' || prev=='A' || prev=='f') { + op = "("; + cp = ")"; + } + if (strlen(yypvt[-3].dynstr) != 0) + sp = " "; + yyval.halves.left = cat(yypvt[-0].halves.left,ds(op),ds("&"), + ds(sp),yypvt[-3].dynstr,ds(sp),NullCP); + yyval.halves.right = cat(ds(cp),yypvt[-0].halves.right,NullCP); + yyval.halves.type = yypvt[-0].halves.type; + prev = 'r'; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", yyval.halves.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", yyval.halves.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", yyval.halves.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 53: + # line 594 "cdgram.y" + { + Debug((stderr, "adecl: opt_constvol_list type\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\ttype='%s'\n", yypvt[-0].dynstr)); + yyval.halves.left = ds(""); + yyval.halves.right = ds(""); + yyval.halves.type = cat(yypvt[-1].dynstr,ds(strlen(yypvt[-1].dynstr)?" ":""),yypvt[-0].dynstr,NullCP); + if (strcmp(yypvt[-0].dynstr, "void") == 0) + prev = 'v'; + else if ((strncmp(yypvt[-0].dynstr, "struct", 6) == 0) || + (strncmp(yypvt[-0].dynstr, "class", 5) == 0)) + prev = 's'; + else + prev = 't'; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", yyval.halves.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", yyval.halves.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", yyval.halves.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } break; + case 54: + # line 617 "cdgram.y" + { + Debug((stderr, "adims: EMPTY\n")); + arbdims = 1; + yyval.dynstr = ds("[]"); + } break; + case 55: + # line 624 "cdgram.y" + { + Debug((stderr, "adims: NUMBER\n")); + Debug((stderr, "\tNUMBER='%s'\n", yypvt[-0].dynstr)); + arbdims = 0; + yyval.dynstr = cat(ds("["),yypvt[-0].dynstr,ds("]"),NullCP); + } break; + case 56: + # line 633 "cdgram.y" + { + Debug((stderr, "type: tinit c_type\n")); + Debug((stderr, "\ttinit=''\n")); + Debug((stderr, "\tc_type='%s'\n", yypvt[-0].dynstr)); + mbcheck(); + yyval.dynstr = yypvt[-0].dynstr; + } break; + case 57: + # line 643 "cdgram.y" + { + Debug((stderr, "tinit: EMPTY\n")); + modbits = 0; + } break; + case 58: + # line 650 "cdgram.y" + { + Debug((stderr, "c_type: mod_list\n")); + Debug((stderr, "\tmod_list='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = yypvt[-0].dynstr; + } break; + case 59: + # line 657 "cdgram.y" + { + Debug((stderr, "c_type: tname\n")); + Debug((stderr, "\ttname='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = yypvt[-0].dynstr; + } break; + case 60: + # line 664 "cdgram.y" + { + Debug((stderr, "c_type: mod_list tname\n")); + Debug((stderr, "\tmod_list='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\ttname='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = cat(yypvt[-1].dynstr,ds(" "),yypvt[-0].dynstr,NullCP); + } break; + case 61: + # line 672 "cdgram.y" + { + Debug((stderr, "c_type: StrClaUniEnum NAME\n")); + Debug((stderr, "\tStrClaUniEnum='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\tNAME='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = cat(yypvt[-1].dynstr,ds(" "),yypvt[-0].dynstr,NullCP); + } break; + case 64: + # line 683 "cdgram.y" + { + yyval.dynstr = yypvt[-0].dynstr; + } break; + case 66: + # line 690 "cdgram.y" + { + yyval.dynstr = yypvt[-0].dynstr; + } break; + case 67: + # line 696 "cdgram.y" + { + Debug((stderr, "tname: INT\n")); + Debug((stderr, "\tINT='%s'\n", yypvt[-0].dynstr)); + modbits |= MB_INT; yyval.dynstr = yypvt[-0].dynstr; + } break; + case 68: + # line 703 "cdgram.y" + { + Debug((stderr, "tname: CHAR\n")); + Debug((stderr, "\tCHAR='%s'\n", yypvt[-0].dynstr)); + modbits |= MB_CHAR; yyval.dynstr = yypvt[-0].dynstr; + } break; + case 69: + # line 710 "cdgram.y" + { + Debug((stderr, "tname: FLOAT\n")); + Debug((stderr, "\tFLOAT='%s'\n", yypvt[-0].dynstr)); + modbits |= MB_FLOAT; yyval.dynstr = yypvt[-0].dynstr; + } break; + case 70: + # line 717 "cdgram.y" + { + Debug((stderr, "tname: DOUBLE\n")); + Debug((stderr, "\tDOUBLE='%s'\n", yypvt[-0].dynstr)); + modbits |= MB_DOUBLE; yyval.dynstr = yypvt[-0].dynstr; + } break; + case 71: + # line 724 "cdgram.y" + { + Debug((stderr, "tname: VOID\n")); + Debug((stderr, "\tVOID='%s'\n", yypvt[-0].dynstr)); + modbits |= MB_VOID; yyval.dynstr = yypvt[-0].dynstr; + } break; + case 72: + # line 732 "cdgram.y" + { + Debug((stderr, "mod_list: modifier mod_list1\n")); + Debug((stderr, "\tmodifier='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\tmod_list1='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = cat(yypvt[-1].dynstr,ds(" "),yypvt[-0].dynstr,NullCP); + } break; + case 73: + # line 740 "cdgram.y" + { + Debug((stderr, "mod_list: modifier\n")); + Debug((stderr, "\tmodifier='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = yypvt[-0].dynstr; + } break; + case 74: + # line 748 "cdgram.y" + { + Debug((stderr, "mod_list1: mod_list\n")); + Debug((stderr, "\tmod_list='%s'\n", yypvt[-0].dynstr)); + yyval.dynstr = yypvt[-0].dynstr; + } break; + case 75: + # line 755 "cdgram.y" + { + Debug((stderr, "mod_list1: CONSTVOLATILE\n")); + Debug((stderr, "\tCONSTVOLATILE='%s'\n", yypvt[-0].dynstr)); + if (PreANSIFlag) + notsupported(" (Pre-ANSI Compiler)", yypvt[-0].dynstr, NullCP); + else if (RitchieFlag) + notsupported(" (Ritchie Compiler)", yypvt[-0].dynstr, NullCP); + else if ((strcmp(yypvt[-0].dynstr, "noalias") == 0) && CplusplusFlag) + unsupp(yypvt[-0].dynstr, NullCP); + yyval.dynstr = yypvt[-0].dynstr; + } break; + case 76: + # line 769 "cdgram.y" + { + Debug((stderr, "modifier: UNSIGNED\n")); + Debug((stderr, "\tUNSIGNED='%s'\n", yypvt[-0].dynstr)); + modbits |= MB_UNSIGNED; yyval.dynstr = yypvt[-0].dynstr; + } break; + case 77: + # line 776 "cdgram.y" + { + Debug((stderr, "modifier: SIGNED\n")); + Debug((stderr, "\tSIGNED='%s'\n", yypvt[-0].dynstr)); + modbits |= MB_SIGNED; yyval.dynstr = yypvt[-0].dynstr; + } break; + case 78: + # line 783 "cdgram.y" + { + Debug((stderr, "modifier: LONG\n")); + Debug((stderr, "\tLONG='%s'\n", yypvt[-0].dynstr)); + modbits |= MB_LONG; yyval.dynstr = yypvt[-0].dynstr; + } break; + case 79: + # line 790 "cdgram.y" + { + Debug((stderr, "modifier: SHORT\n")); + Debug((stderr, "\tSHORT='%s'\n", yypvt[-0].dynstr)); + modbits |= MB_SHORT; yyval.dynstr = yypvt[-0].dynstr; + } break; + case 80: + # line 798 "cdgram.y" + { + Debug((stderr, "opt_constvol_list: CONSTVOLATILE opt_constvol_list\n")); + Debug((stderr, "\tCONSTVOLATILE='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\topt_constvol_list='%s'\n", yypvt[-0].dynstr)); + if (PreANSIFlag) + notsupported(" (Pre-ANSI Compiler)", yypvt[-1].dynstr, NullCP); + else if (RitchieFlag) + notsupported(" (Ritchie Compiler)", yypvt[-1].dynstr, NullCP); + else if ((strcmp(yypvt[-1].dynstr, "noalias") == 0) && CplusplusFlag) + unsupp(yypvt[-1].dynstr, NullCP); + yyval.dynstr = cat(yypvt[-1].dynstr,ds(strlen(yypvt[-0].dynstr) ? " " : ""),yypvt[-0].dynstr,NullCP); + } break; + case 81: + # line 812 "cdgram.y" + { + Debug((stderr, "opt_constvol_list: EMPTY\n")); + yyval.dynstr = ds(""); + } break; + case 82: + # line 819 "cdgram.y" + { + Debug((stderr, "constvol_list: CONSTVOLATILE opt_constvol_list\n")); + Debug((stderr, "\tCONSTVOLATILE='%s'\n", yypvt[-1].dynstr)); + Debug((stderr, "\topt_constvol_list='%s'\n", yypvt[-0].dynstr)); + if (PreANSIFlag) + notsupported(" (Pre-ANSI Compiler)", yypvt[-1].dynstr, NullCP); + else if (RitchieFlag) + notsupported(" (Ritchie Compiler)", yypvt[-1].dynstr, NullCP); + else if ((strcmp(yypvt[-1].dynstr, "noalias") == 0) && CplusplusFlag) + unsupp(yypvt[-1].dynstr, NullCP); + yyval.dynstr = cat(yypvt[-1].dynstr,ds(strlen(yypvt[-0].dynstr) ? " " : ""),yypvt[-0].dynstr,NullCP); + } break; + case 86: + # line 837 "cdgram.y" + { + Debug((stderr, "storage: AUTO,EXTERN,STATIC,REGISTER (%s)\n", yypvt[-0].dynstr)); + yyval.dynstr = yypvt[-0].dynstr; + } break; + case 87: + # line 844 "cdgram.y" + { + Debug((stderr, "opt_storage: storage=%s\n", yypvt[-0].dynstr)); + yyval.dynstr = yypvt[-0].dynstr; + } break; + case 88: + # line 850 "cdgram.y" + { + Debug((stderr, "opt_storage: EMPTY\n")); + yyval.dynstr = ds(""); + } break; + } + goto yystack; /* stack new state and value */ + + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdgram.y.in diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdgram.y.in:1.1 *** /dev/null Tue Oct 5 14:08:39 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdgram.y.in Tue Oct 5 14:08:26 2004 *************** *** 0 **** --- 1,855 ---- + %{ + /* Yacc grammar for ANSI and C++ cdecl. */ + /* The output of this file is included */ + /* into the C file cdecl.c. */ + char cdgramsccsid[] = "@(#)cdgram.y 2.2 3/30/88"; + %} + + %union { + char *dynstr; + struct { + char *left; + char *right; + char *type; + } halves; + } + + %token ARRAY AS CAST COMMA DECLARE DOUBLECOLON EXPLAIN FUNCTION + %token HELP INTO OF MEMBER POINTER REFERENCE RETURNING SET TO + %token CHAR CLASS CONSTVOLATILE DOUBLE ENUM FLOAT INT LONG NAME + %token NUMBER SHORT SIGNED STRUCT UNION UNSIGNED VOID + %token AUTO EXTERN REGISTER STATIC + %type adecllist adims c_type cast castlist cdecl cdecl1 cdims + %type constvol_list ClassStruct mod_list mod_list1 modifier + %type opt_constvol_list optNAME opt_storage storage StrClaUniEnum + %type tname type + %type adecl + + %start prog + + %% + prog : /* empty */ + | prog stmt + { + prompt(); + prev = 0; + } + ; + + stmt : HELP NL + { + Debug((stderr, "stmt: help\n")); + dohelp(); + } + + | DECLARE NAME AS opt_storage adecl NL + { + Debug((stderr, "stmt: DECLARE NAME AS opt_storage adecl\n")); + Debug((stderr, "\tNAME='%s'\n", $2)); + Debug((stderr, "\topt_storage='%s'\n", $4)); + Debug((stderr, "\tacdecl.left='%s'\n", $5.left)); + Debug((stderr, "\tacdecl.right='%s'\n", $5.right)); + Debug((stderr, "\tacdecl.type='%s'\n", $5.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + dodeclare($2, $4, $5.left, $5.right, $5.type); + } + + | DECLARE opt_storage adecl NL + { + Debug((stderr, "stmt: DECLARE opt_storage adecl\n")); + Debug((stderr, "\topt_storage='%s'\n", $2)); + Debug((stderr, "\tacdecl.left='%s'\n", $3.left)); + Debug((stderr, "\tacdecl.right='%s'\n", $3.right)); + Debug((stderr, "\tacdecl.type='%s'\n", $3.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + dodeclare(NullCP, $2, $3.left, $3.right, $3.type); + } + + | CAST NAME INTO adecl NL + { + Debug((stderr, "stmt: CAST NAME AS adecl\n")); + Debug((stderr, "\tNAME='%s'\n", $2)); + Debug((stderr, "\tacdecl.left='%s'\n", $4.left)); + Debug((stderr, "\tacdecl.right='%s'\n", $4.right)); + Debug((stderr, "\tacdecl.type='%s'\n", $4.type)); + docast($2, $4.left, $4.right, $4.type); + } + + | CAST adecl NL + { + Debug((stderr, "stmt: CAST adecl\n")); + Debug((stderr, "\tacdecl.left='%s'\n", $2.left)); + Debug((stderr, "\tacdecl.right='%s'\n", $2.right)); + Debug((stderr, "\tacdecl.type='%s'\n", $2.type)); + docast(NullCP, $2.left, $2.right, $2.type); + } + + | EXPLAIN opt_storage opt_constvol_list type cdecl NL + { + Debug((stderr, "stmt: EXPLAIN opt_storage opt_constvol_list type cdecl\n")); + Debug((stderr, "\topt_storage='%s'\n", $2)); + Debug((stderr, "\topt_constvol_list='%s'\n", $3)); + Debug((stderr, "\ttype='%s'\n", $4)); + Debug((stderr, "\tcdecl='%s'\n", $5)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + dodexplain($2, $3, $4, $5); + } + + | EXPLAIN storage opt_constvol_list cdecl NL + { + Debug((stderr, "stmt: EXPLAIN storage opt_constvol_list cdecl\n")); + Debug((stderr, "\tstorage='%s'\n", $2)); + Debug((stderr, "\topt_constvol_list='%s'\n", $3)); + Debug((stderr, "\tcdecl='%s'\n", $4)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + dodexplain($2, $3, NullCP, $4); + } + + | EXPLAIN opt_storage constvol_list cdecl NL + { + Debug((stderr, "stmt: EXPLAIN opt_storage constvol_list cdecl\n")); + Debug((stderr, "\topt_storage='%s'\n", $2)); + Debug((stderr, "\tconstvol_list='%s'\n", $3)); + Debug((stderr, "\tcdecl='%s'\n", $4)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + dodexplain($2, $3, NullCP, $4); + } + + | EXPLAIN '(' opt_constvol_list type cast ')' optNAME NL + { + Debug((stderr, "stmt: EXPLAIN ( opt_constvol_list type cast ) optNAME\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", $3)); + Debug((stderr, "\ttype='%s'\n", $4)); + Debug((stderr, "\tcast='%s'\n", $5)); + Debug((stderr, "\tNAME='%s'\n", $7)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + docexplain($3, $4, $5, $7); + } + + | SET optNAME NL + { + Debug((stderr, "stmt: SET optNAME\n")); + Debug((stderr, "\toptNAME='%s'\n", $2)); + doset($2); + } + + | NL + | error NL + { + yyerrok; + } + ; + + NL : '\n' + { + doprompt(); + } + | ';' + { + noprompt(); + } + ; + + optNAME : NAME + { + Debug((stderr, "optNAME: NAME\n")); + Debug((stderr, "\tNAME='%s'\n", $1)); + $$ = $1; + } + + | /* empty */ + { + Debug((stderr, "optNAME: EMPTY\n")); + $$ = ds(unknown_name); + } + ; + + cdecl : cdecl1 + | '*' opt_constvol_list cdecl + { + Debug((stderr, "cdecl: * opt_constvol_list cdecl\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", $2)); + Debug((stderr, "\tcdecl='%s'\n", $3)); + $$ = cat($3,$2,ds(strlen($2)?" pointer to ":"pointer to "),NullCP); + prev = 'p'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | NAME DOUBLECOLON '*' cdecl + { + Debug((stderr, "cdecl: NAME DOUBLECOLON '*' cdecl\n")); + Debug((stderr, "\tNAME='%s'\n", $1)); + Debug((stderr, "\tcdecl='%s'\n", $4)); + if (!CplusplusFlag) + unsupp("pointer to member of class", NullCP); + $$ = cat($4,ds("pointer to member of class "),$1,ds(" "),NullCP); + prev = 'p'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | '&' opt_constvol_list cdecl + { + Debug((stderr, "cdecl: & opt_constvol_list cdecl\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", $2)); + Debug((stderr, "\tcdecl='%s'\n", $3)); + if (!CplusplusFlag) + unsupp("reference", NullCP); + $$ = cat($3,$2,ds(strlen($2)?" reference to ":"reference to "),NullCP); + prev = 'r'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + ; + + cdecl1 : cdecl1 '(' ')' + { + Debug((stderr, "cdecl1: cdecl1()\n")); + Debug((stderr, "\tcdecl1='%s'\n", $1)); + $$ = cat($1,ds("function returning "),NullCP); + prev = 'f'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | cdecl1 '(' castlist ')' + { + Debug((stderr, "cdecl1: cdecl1(castlist)\n")); + Debug((stderr, "\tcdecl1='%s'\n", $1)); + Debug((stderr, "\tcastlist='%s'\n", $3)); + $$ = cat($1, ds("function ("), + $3, ds(") returning "), NullCP); + prev = 'f'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | cdecl1 cdims + { + Debug((stderr, "cdecl1: cdecl1 cdims\n")); + Debug((stderr, "\tcdecl1='%s'\n", $1)); + Debug((stderr, "\tcdims='%s'\n", $2)); + $$ = cat($1,ds("array "),$2,NullCP); + prev = 'a'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | '(' cdecl ')' + { + Debug((stderr, "cdecl1: (cdecl)\n")); + Debug((stderr, "\tcdecl='%s'\n", $2)); + $$ = $2; + /* prev = prev; */ + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | NAME + { + Debug((stderr, "cdecl1: NAME\n")); + Debug((stderr, "\tNAME='%s'\n", $1)); + savedname = $1; + $$ = ds(""); + prev = 'n'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + ; + + castlist : castlist COMMA castlist + { + Debug((stderr, "castlist: castlist1, castlist2\n")); + Debug((stderr, "\tcastlist1='%s'\n", $1)); + Debug((stderr, "\tcastlist2='%s'\n", $3)); + $$ = cat($1, ds(", "), $3, NullCP); + } + + | opt_constvol_list type cast + { + Debug((stderr, "castlist: opt_constvol_list type cast\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", $1)); + Debug((stderr, "\ttype='%s'\n", $2)); + Debug((stderr, "\tcast='%s'\n", $3)); + $$ = cat($3, $1, ds(strlen($1) ? " " : ""), $2, NullCP); + } + + | NAME + { + $$ = $1; + } + ; + + adecllist : /* empty */ + { + Debug((stderr, "adecllist: EMPTY\n")); + $$ = ds(""); + } + + | adecllist COMMA adecllist + { + Debug((stderr, "adecllist: adecllist1, adecllist2\n")); + Debug((stderr, "\tadecllist1='%s'\n", $1)); + Debug((stderr, "\tadecllist2='%s'\n", $3)); + $$ = cat($1, ds(", "), $3, NullCP); + } + + | NAME + { + Debug((stderr, "adecllist: NAME\n")); + Debug((stderr, "\tNAME='%s'\n", $1)); + $$ = $1; + } + + | adecl + { + Debug((stderr, "adecllist: adecl\n")); + Debug((stderr, "\tadecl.left='%s'\n", $1.left)); + Debug((stderr, "\tadecl.right='%s'\n", $1.right)); + Debug((stderr, "\tadecl.type='%s'\n", $1.type)); + $$ = cat($1.type, ds(" "), $1.left, $1.right, NullCP); + } + + | NAME AS adecl + { + Debug((stderr, "adecllist: NAME AS adecl\n")); + Debug((stderr, "\tNAME='%s'\n", $1)); + Debug((stderr, "\tadecl.left='%s'\n", $3.left)); + Debug((stderr, "\tadecl.right='%s'\n", $3.right)); + Debug((stderr, "\tadecl.type='%s'\n", $3.type)); + $$ = cat($3.type, ds(" "), $3.left, $1, $3.right, NullCP); + } + ; + + cast : /* empty */ + { + Debug((stderr, "cast: EMPTY\n")); + $$ = ds(""); + /* prev = prev; */ + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | '(' ')' + { + Debug((stderr, "cast: ()\n")); + $$ = ds("function returning "); + prev = 'f'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | '(' cast ')' '(' ')' + { + Debug((stderr, "cast: (cast)()\n")); + Debug((stderr, "\tcast='%s'\n", $2)); + $$ = cat($2,ds("function returning "),NullCP); + prev = 'f'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | '(' cast ')' '(' castlist ')' + { + Debug((stderr, "cast: (cast)(castlist)\n")); + Debug((stderr, "\tcast='%s'\n", $2)); + Debug((stderr, "\tcastlist='%s'\n", $5)); + $$ = cat($2,ds("function ("),$5,ds(") returning "),NullCP); + prev = 'f'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | '(' cast ')' + { + Debug((stderr, "cast: (cast)\n")); + Debug((stderr, "\tcast='%s'\n", $2)); + $$ = $2; + /* prev = prev; */ + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | NAME DOUBLECOLON '*' cast + { + Debug((stderr, "cast: NAME::*cast\n")); + Debug((stderr, "\tcast='%s'\n", $4)); + if (!CplusplusFlag) + unsupp("pointer to member of class", NullCP); + $$ = cat($4,ds("pointer to member of class "),$1,ds(" "),NullCP); + prev = 'p'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | '*' cast + { + Debug((stderr, "cast: *cast\n")); + Debug((stderr, "\tcast='%s'\n", $2)); + $$ = cat($2,ds("pointer to "),NullCP); + prev = 'p'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | '&' cast + { + Debug((stderr, "cast: &cast\n")); + Debug((stderr, "\tcast='%s'\n", $2)); + if (!CplusplusFlag) + unsupp("reference", NullCP); + $$ = cat($2,ds("reference to "),NullCP); + prev = 'r'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | cast cdims + { + Debug((stderr, "cast: cast cdims\n")); + Debug((stderr, "\tcast='%s'\n", $1)); + Debug((stderr, "\tcdims='%s'\n", $2)); + $$ = cat($1,ds("array "),$2,NullCP); + prev = 'a'; + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + ; + + cdims : '[' ']' + { + Debug((stderr, "cdims: []\n")); + $$ = ds("of "); + } + + | '[' NUMBER ']' + { + Debug((stderr, "cdims: [NUMBER]\n")); + Debug((stderr, "\tNUMBER='%s'\n", $2)); + $$ = cat($2,ds(" of "),NullCP); + } + ; + + adecl : FUNCTION RETURNING adecl + { + Debug((stderr, "adecl: FUNCTION RETURNING adecl\n")); + Debug((stderr, "\tadecl.left='%s'\n", $3.left)); + Debug((stderr, "\tadecl.right='%s'\n", $3.right)); + Debug((stderr, "\tadecl.type='%s'\n", $3.type)); + if (prev == 'f') + unsupp("Function returning function", + "function returning pointer to function"); + else if (prev=='A' || prev=='a') + unsupp("Function returning array", + "function returning pointer"); + $$.left = $3.left; + $$.right = cat(ds("()"),$3.right,NullCP); + $$.type = $3.type; + prev = 'f'; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", $$.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", $$.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", $$.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | FUNCTION '(' adecllist ')' RETURNING adecl + { + Debug((stderr, "adecl: FUNCTION (adecllist) RETURNING adecl\n")); + Debug((stderr, "\tadecllist='%s'\n", $3)); + Debug((stderr, "\tadecl.left='%s'\n", $6.left)); + Debug((stderr, "\tadecl.right='%s'\n", $6.right)); + Debug((stderr, "\tadecl.type='%s'\n", $6.type)); + if (prev == 'f') + unsupp("Function returning function", + "function returning pointer to function"); + else if (prev=='A' || prev=='a') + unsupp("Function returning array", + "function returning pointer"); + $$.left = $6.left; + $$.right = cat(ds("("),$3,ds(")"),$6.right,NullCP); + $$.type = $6.type; + prev = 'f'; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", $$.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", $$.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", $$.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | ARRAY adims OF adecl + { + Debug((stderr, "adecl: ARRAY adims OF adecl\n")); + Debug((stderr, "\tadims='%s'\n", $2)); + Debug((stderr, "\tadecl.left='%s'\n", $4.left)); + Debug((stderr, "\tadecl.right='%s'\n", $4.right)); + Debug((stderr, "\tadecl.type='%s'\n", $4.type)); + if (prev == 'f') + unsupp("Array of function", + "array of pointer to function"); + else if (prev == 'a') + unsupp("Inner array of unspecified size", + "array of pointer"); + else if (prev == 'v') + unsupp("Array of void", + "pointer to void"); + if (arbdims) + prev = 'a'; + else + prev = 'A'; + $$.left = $4.left; + $$.right = cat($2,$4.right,NullCP); + $$.type = $4.type; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", $$.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", $$.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", $$.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | opt_constvol_list POINTER TO adecl + { + char *op = "", *cp = "", *sp = ""; + + Debug((stderr, "adecl: opt_constvol_list POINTER TO adecl\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", $1)); + Debug((stderr, "\tadecl.left='%s'\n", $4.left)); + Debug((stderr, "\tadecl.right='%s'\n", $4.right)); + Debug((stderr, "\tadecl.type='%s'\n", $4.type)); + if (prev == 'a') + unsupp("Pointer to array of unspecified dimension", + "pointer to object"); + if (prev=='a' || prev=='A' || prev=='f') { + op = "("; + cp = ")"; + } + if (strlen($1) != 0) + sp = " "; + $$.left = cat($4.left,ds(op),ds("*"), + ds(sp),$1,ds(sp),NullCP); + $$.right = cat(ds(cp),$4.right,NullCP); + $$.type = $4.type; + prev = 'p'; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", $$.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", $$.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", $$.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | opt_constvol_list POINTER TO MEMBER OF ClassStruct NAME adecl + { + char *op = "", *cp = "", *sp = ""; + + Debug((stderr, "adecl: opt_constvol_list POINTER TO MEMBER OF ClassStruct NAME adecl\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", $1)); + Debug((stderr, "\tClassStruct='%s'\n", $6)); + Debug((stderr, "\tNAME='%s'\n", $7)); + Debug((stderr, "\tadecl.left='%s'\n", $8.left)); + Debug((stderr, "\tadecl.right='%s'\n", $8.right)); + Debug((stderr, "\tadecl.type='%s'\n", $8.type)); + if (!CplusplusFlag) + unsupp("pointer to member of class", NullCP); + if (prev == 'a') + unsupp("Pointer to array of unspecified dimension", + "pointer to object"); + if (prev=='a' || prev=='A' || prev=='f') { + op = "("; + cp = ")"; + } + if (strlen($1) != 0) + sp = " "; + $$.left = cat($8.left,ds(op),$7,ds("::*"), + ds(sp),$1,ds(sp),NullCP); + $$.right = cat(ds(cp),$8.right,NullCP); + $$.type = $8.type; + prev = 'p'; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", $$.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", $$.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", $$.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | opt_constvol_list REFERENCE TO adecl + { + char *op = "", *cp = "", *sp = ""; + + Debug((stderr, "adecl: opt_constvol_list REFERENCE TO adecl\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", $1)); + Debug((stderr, "\tadecl.left='%s'\n", $4.left)); + Debug((stderr, "\tadecl.right='%s'\n", $4.right)); + Debug((stderr, "\tadecl.type='%s'\n", $4.type)); + if (!CplusplusFlag) + unsupp("reference", NullCP); + if (prev == 'v') + unsupp("Reference to void", + "pointer to void"); + else if (prev == 'a') + unsupp("Reference to array of unspecified dimension", + "reference to object"); + if (prev=='a' || prev=='A' || prev=='f') { + op = "("; + cp = ")"; + } + if (strlen($1) != 0) + sp = " "; + $$.left = cat($4.left,ds(op),ds("&"), + ds(sp),$1,ds(sp),NullCP); + $$.right = cat(ds(cp),$4.right,NullCP); + $$.type = $4.type; + prev = 'r'; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", $$.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", $$.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", $$.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + + | opt_constvol_list type + { + Debug((stderr, "adecl: opt_constvol_list type\n")); + Debug((stderr, "\topt_constvol_list='%s'\n", $1)); + Debug((stderr, "\ttype='%s'\n", $2)); + $$.left = ds(""); + $$.right = ds(""); + $$.type = cat($1,ds(strlen($1)?" ":""),$2,NullCP); + if (strcmp($2, "void") == 0) + prev = 'v'; + else if ((strncmp($2, "struct", 6) == 0) || + (strncmp($2, "class", 5) == 0)) + prev = 's'; + else + prev = 't'; + Debug((stderr, "\n\tadecl now =\n")); + Debug((stderr, "\t\tadecl.left='%s'\n", $$.left)); + Debug((stderr, "\t\tadecl.right='%s'\n", $$.right)); + Debug((stderr, "\t\tadecl.type='%s'\n", $$.type)); + Debug((stderr, "\tprev = '%s'\n", visible(prev))); + } + ; + + adims : /* empty */ + { + Debug((stderr, "adims: EMPTY\n")); + arbdims = 1; + $$ = ds("[]"); + } + + | NUMBER + { + Debug((stderr, "adims: NUMBER\n")); + Debug((stderr, "\tNUMBER='%s'\n", $1)); + arbdims = 0; + $$ = cat(ds("["),$1,ds("]"),NullCP); + } + ; + + type : tinit c_type + { + Debug((stderr, "type: tinit c_type\n")); + Debug((stderr, "\ttinit=''\n")); + Debug((stderr, "\tc_type='%s'\n", $2)); + mbcheck(); + $$ = $2; + } + ; + + tinit : /* empty */ + { + Debug((stderr, "tinit: EMPTY\n")); + modbits = 0; + } + ; + + c_type : mod_list + { + Debug((stderr, "c_type: mod_list\n")); + Debug((stderr, "\tmod_list='%s'\n", $1)); + $$ = $1; + } + + | tname + { + Debug((stderr, "c_type: tname\n")); + Debug((stderr, "\ttname='%s'\n", $1)); + $$ = $1; + } + + | mod_list tname + { + Debug((stderr, "c_type: mod_list tname\n")); + Debug((stderr, "\tmod_list='%s'\n", $1)); + Debug((stderr, "\ttname='%s'\n", $2)); + $$ = cat($1,ds(" "),$2,NullCP); + } + + | StrClaUniEnum NAME + { + Debug((stderr, "c_type: StrClaUniEnum NAME\n")); + Debug((stderr, "\tStrClaUniEnum='%s'\n", $1)); + Debug((stderr, "\tNAME='%s'\n", $2)); + $$ = cat($1,ds(" "),$2,NullCP); + } + ; + + StrClaUniEnum : ClassStruct + | ENUM + | UNION + { + $$ = $1; + } + ; + + ClassStruct : STRUCT + | CLASS + { + $$ = $1; + } + ; + + tname : INT + { + Debug((stderr, "tname: INT\n")); + Debug((stderr, "\tINT='%s'\n", $1)); + modbits |= MB_INT; $$ = $1; + } + + | CHAR + { + Debug((stderr, "tname: CHAR\n")); + Debug((stderr, "\tCHAR='%s'\n", $1)); + modbits |= MB_CHAR; $$ = $1; + } + + | FLOAT + { + Debug((stderr, "tname: FLOAT\n")); + Debug((stderr, "\tFLOAT='%s'\n", $1)); + modbits |= MB_FLOAT; $$ = $1; + } + + | DOUBLE + { + Debug((stderr, "tname: DOUBLE\n")); + Debug((stderr, "\tDOUBLE='%s'\n", $1)); + modbits |= MB_DOUBLE; $$ = $1; + } + + | VOID + { + Debug((stderr, "tname: VOID\n")); + Debug((stderr, "\tVOID='%s'\n", $1)); + modbits |= MB_VOID; $$ = $1; + } + ; + + mod_list : modifier mod_list1 + { + Debug((stderr, "mod_list: modifier mod_list1\n")); + Debug((stderr, "\tmodifier='%s'\n", $1)); + Debug((stderr, "\tmod_list1='%s'\n", $2)); + $$ = cat($1,ds(" "),$2,NullCP); + } + + | modifier + { + Debug((stderr, "mod_list: modifier\n")); + Debug((stderr, "\tmodifier='%s'\n", $1)); + $$ = $1; + } + ; + + mod_list1 : mod_list + { + Debug((stderr, "mod_list1: mod_list\n")); + Debug((stderr, "\tmod_list='%s'\n", $1)); + $$ = $1; + } + + | CONSTVOLATILE + { + Debug((stderr, "mod_list1: CONSTVOLATILE\n")); + Debug((stderr, "\tCONSTVOLATILE='%s'\n", $1)); + if (PreANSIFlag) + notsupported(" (Pre-ANSI Compiler)", $1, NullCP); + else if (RitchieFlag) + notsupported(" (Ritchie Compiler)", $1, NullCP); + else if ((strcmp($1, "noalias") == 0) && CplusplusFlag) + unsupp($1, NullCP); + $$ = $1; + } + ; + + modifier : UNSIGNED + { + Debug((stderr, "modifier: UNSIGNED\n")); + Debug((stderr, "\tUNSIGNED='%s'\n", $1)); + modbits |= MB_UNSIGNED; $$ = $1; + } + + | SIGNED + { + Debug((stderr, "modifier: SIGNED\n")); + Debug((stderr, "\tSIGNED='%s'\n", $1)); + modbits |= MB_SIGNED; $$ = $1; + } + + | LONG + { + Debug((stderr, "modifier: LONG\n")); + Debug((stderr, "\tLONG='%s'\n", $1)); + modbits |= MB_LONG; $$ = $1; + } + + | SHORT + { + Debug((stderr, "modifier: SHORT\n")); + Debug((stderr, "\tSHORT='%s'\n", $1)); + modbits |= MB_SHORT; $$ = $1; + } + ; + + opt_constvol_list: CONSTVOLATILE opt_constvol_list + { + Debug((stderr, "opt_constvol_list: CONSTVOLATILE opt_constvol_list\n")); + Debug((stderr, "\tCONSTVOLATILE='%s'\n", $1)); + Debug((stderr, "\topt_constvol_list='%s'\n", $2)); + if (PreANSIFlag) + notsupported(" (Pre-ANSI Compiler)", $1, NullCP); + else if (RitchieFlag) + notsupported(" (Ritchie Compiler)", $1, NullCP); + else if ((strcmp($1, "noalias") == 0) && CplusplusFlag) + unsupp($1, NullCP); + $$ = cat($1,ds(strlen($2) ? " " : ""),$2,NullCP); + } + + | /* empty */ + { + Debug((stderr, "opt_constvol_list: EMPTY\n")); + $$ = ds(""); + } + ; + + constvol_list: CONSTVOLATILE opt_constvol_list + { + Debug((stderr, "constvol_list: CONSTVOLATILE opt_constvol_list\n")); + Debug((stderr, "\tCONSTVOLATILE='%s'\n", $1)); + Debug((stderr, "\topt_constvol_list='%s'\n", $2)); + if (PreANSIFlag) + notsupported(" (Pre-ANSI Compiler)", $1, NullCP); + else if (RitchieFlag) + notsupported(" (Ritchie Compiler)", $1, NullCP); + else if ((strcmp($1, "noalias") == 0) && CplusplusFlag) + unsupp($1, NullCP); + $$ = cat($1,ds(strlen($2) ? " " : ""),$2,NullCP); + } + ; + + storage : AUTO + | EXTERN + | REGISTER + | STATIC + { + Debug((stderr, "storage: AUTO,EXTERN,STATIC,REGISTER (%s)\n", $1)); + $$ = $1; + } + ; + + opt_storage : storage + { + Debug((stderr, "opt_storage: storage=%s\n", $1)); + $$ = $1; + } + + | /* empty */ + { + Debug((stderr, "opt_storage: EMPTY\n")); + $$ = ds(""); + } + ; + %% Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdlex.c.source diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdlex.c.source:1.1 *** /dev/null Tue Oct 5 14:08:40 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdlex.c.source Tue Oct 5 14:08:26 2004 *************** *** 0 **** --- 1,1702 ---- + #include + # define U(x) x + # define NLSTATE yyprevious=YYNEWLINE + # define BEGIN yybgin = yysvec + 1 + + # define INITIAL 0 + # define YYLERR yysvec + # define YYSTATE (yyestate-yysvec-1) + # define YYOPTIM 1 + # define YYLMAX BUFSIZ + #ifndef __cplusplus + # define output(c) (void)putc(c,yyout) + #else + # define lex_output(c) (void)putc(c,yyout) + #endif + + #if defined(__cplusplus) || defined(__STDC__) + + #if defined(__cplusplus) && defined(__EXTERN_C__) + extern "C" { + #endif + int yyback(int *, int); + int yyinput(void); + int yylook(void); + void yyoutput(int); + int yyracc(int); + int yyreject(void); + void yyunput(int); + int yylex(void); + #ifdef YYLEX_E + void yywoutput(wchar_t); + wchar_t yywinput(void); + #endif + #ifndef yyless + int yyless(int); + #endif + #ifndef yywrap + int yywrap_nasko(void); + #endif + #ifdef LEXDEBUG + void allprint(char); + void sprint(char *); + #endif + #if defined(__cplusplus) && defined(__EXTERN_C__) + } + #endif + + #ifdef __cplusplus + extern "C" { + #endif + void exit(int); + #ifdef __cplusplus + } + #endif + + #endif + # define unput(c) {yytchar= (c);if(yytchar=='\n')yylineno--;*yysptr++=yytchar;} + # define yymore() (yymorfg=1) + #ifndef __cplusplus + # define input() (((yytchar=yysptr>yysbuf?U(*--yysptr):getc(yyin))==10?(yylineno++,yytchar):yytchar)==EOF?0:yytchar) + #else + # define lex_input() (((yytchar=yysptr>yysbuf?U(*--yysptr):getc(yyin))==10?(yylineno++,yytchar):yytchar)==EOF?0:yytchar) + #endif + #define ECHO fprintf(yyout, "%s",yytext) + # define REJECT { nstr = yyreject(); goto yyfussy;} + int yyleng; + char yytext[YYLMAX]; + int yymorfg; + extern char *yysptr, yysbuf[]; + int yytchar; + FILE *yyin = 0, *yyout = 0; + extern int yylineno; + struct yysvf { + struct yywork *yystoff; + struct yysvf *yyother; + int *yystops;}; + struct yysvf *yyestate; + extern struct yysvf yysvec[], *yybgin; + + # line 3 "cdlex.l" + /* Lexical analyzer description for ANSI and C++ cdecl. */ + + # line 4 "cdlex.l" + /* The output of this file is included */ + + # line 5 "cdlex.l" + /* into the C file cdecl.c. */ + char cdlexsccsid[] = "@(#)cdlex.l 2.2 3/30/88"; + # define YYNEWLINE 10 + yylex(){ + if (yyin == 0) { yyin = stdin; yyin = stdout; } + int nstr; extern int yyprevious; + #ifdef __cplusplus + /* to avoid CC and lint complaining yyfussy not being used ...*/ + static int __lex_hack = 0; + if (__lex_hack) goto yyfussy; + #endif + while((nstr = yylook()) >= 0) + yyfussy: switch(nstr){ + case 0: + if(yywrap_nasko()) return(0); break; + case 1: + + # line 13 "cdlex.l" + return ARRAY; + break; + case 2: + + # line 14 "cdlex.l" + return AS; + break; + case 3: + + # line 15 "cdlex.l" + return CAST; + break; + case 4: + + # line 16 "cdlex.l" + return DECLARE; + break; + case 5: + + # line 17 "cdlex.l" + return 0; + break; + case 6: + + # line 18 "cdlex.l" + return EXPLAIN; + break; + case 7: + + # line 19 "cdlex.l" + return FUNCTION; + break; + case 8: + + # line 20 "cdlex.l" + return FUNCTION; + break; + case 9: + + # line 21 "cdlex.l" + return HELP; + break; + case 10: + + # line 22 "cdlex.l" + return INTO; + break; + case 11: + + # line 23 "cdlex.l" + return MEMBER; + break; + case 12: + + # line 24 "cdlex.l" + return OF; + break; + case 13: + + # line 25 "cdlex.l" + return POINTER; + break; + case 14: + + # line 26 "cdlex.l" + return POINTER; + break; + case 15: + + # line 27 "cdlex.l" + return 0; + break; + case 16: + + # line 28 "cdlex.l" + return REFERENCE; + break; + case 17: + + # line 29 "cdlex.l" + return REFERENCE; + break; + case 18: + + # line 30 "cdlex.l" + return RETURNING; + break; + case 19: + + # line 31 "cdlex.l" + return RETURNING; + break; + case 20: + + # line 32 "cdlex.l" + return SET; + break; + case 21: + + # line 33 "cdlex.l" + return TO; + break; + case 22: + + # line 34 "cdlex.l" + return ARRAY; + break; + case 23: + + # line 35 "cdlex.l" + return DOUBLECOLON; + break; + case 24: + + # line 36 "cdlex.l" + return HELP; + break; + case 25: + + # line 37 "cdlex.l" + return COMMA; + break; + case 26: + + # line 39 "cdlex.l" + { yylval.dynstr = ds(yytext); return AUTO; } + break; + case 27: + + # line 40 "cdlex.l" + { yylval.dynstr = ds("char"); return CHAR; } + break; + case 28: + + # line 41 "cdlex.l" + { yylval.dynstr = ds(yytext); return CHAR; } + break; + case 29: + + # line 42 "cdlex.l" + { yylval.dynstr = ds(yytext); return CLASS; } + break; + case 30: + + # line 43 "cdlex.l" + { yylval.dynstr = ds("const"); return CONSTVOLATILE; } + break; + case 31: + + # line 44 "cdlex.l" + { yylval.dynstr = ds(yytext); return CONSTVOLATILE; } + break; + case 32: + + # line 45 "cdlex.l" + { yylval.dynstr = ds(yytext); return DOUBLE; } + break; + case 33: + + # line 46 "cdlex.l" + { yylval.dynstr = ds("enum"); return ENUM; } + break; + case 34: + + # line 47 "cdlex.l" + { yylval.dynstr = ds(yytext); return ENUM; } + break; + case 35: + + # line 48 "cdlex.l" + { yylval.dynstr = ds(yytext); return EXTERN; } + break; + case 36: + + # line 49 "cdlex.l" + { yylval.dynstr = ds(yytext); return FLOAT; } + break; + case 37: + + # line 50 "cdlex.l" + { yylval.dynstr = ds("int"); return INT; } + break; + case 38: + + # line 51 "cdlex.l" + { yylval.dynstr = ds(yytext); return INT; } + break; + case 39: + + # line 52 "cdlex.l" + { yylval.dynstr = ds(yytext); return LONG; } + break; + case 40: + + # line 53 "cdlex.l" + { yylval.dynstr = ds(yytext); return CONSTVOLATILE; } + break; + case 41: + + # line 54 "cdlex.l" + { yylval.dynstr = ds(yytext); return REGISTER; } + break; + case 42: + + # line 55 "cdlex.l" + { yylval.dynstr = ds(yytext); return SHORT; } + break; + case 43: + + # line 56 "cdlex.l" + { yylval.dynstr = ds(yytext); return SIGNED; } + break; + case 44: + + # line 57 "cdlex.l" + { yylval.dynstr = ds(yytext); return STATIC; } + break; + case 45: + + # line 58 "cdlex.l" + { yylval.dynstr = ds("struct"); return STRUCT; } + break; + case 46: + + # line 59 "cdlex.l" + { yylval.dynstr = ds(yytext); return STRUCT; } + break; + case 47: + + # line 60 "cdlex.l" + { yylval.dynstr = ds(yytext); return UNION; } + break; + case 48: + + # line 61 "cdlex.l" + { yylval.dynstr = ds(yytext); return UNSIGNED; } + break; + case 49: + + # line 62 "cdlex.l" + { yylval.dynstr = ds(yytext); return VOID; } + break; + case 50: + + # line 63 "cdlex.l" + { yylval.dynstr = ds(yytext); return CONSTVOLATILE; } + break; + case 51: + + # line 65 "cdlex.l" + { yylval.dynstr = ds(yytext); return NAME; } + break; + case 52: + + # line 66 "cdlex.l" + { yylval.dynstr = ds(yytext); return NUMBER; } + break; + case 53: + + # line 68 "cdlex.l" + ; + break; + case 54: + + # line 69 "cdlex.l" + ; + break; + case 55: + + # line 70 "cdlex.l" + return *yytext; + break; + case 56: + + # line 71 "cdlex.l" + { + (void) printf("bad character '%s'\n",visible(*yytext)); + return *yytext; + } + break; + case -1: + break; + default: + (void)fprintf(yyout,"bad switch yylook %d",nstr); + } return(0); } + /* end of yylex */ + int yyvstop[] = { + 0, + + 56, + 0, + + 54, + 56, + 0, + + 55, + 0, + + 53, + 56, + 0, + + 55, + 56, + 0, + + 25, + 56, + 0, + + 52, + 56, + 0, + + 56, + 0, + + 24, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 51, + 56, + 0, + + 53, + 0, + + 52, + 0, + + 23, + 0, + + 51, + 0, + + 51, + 0, + + 2, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 12, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 21, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 38, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 14, + 51, + 0, + + 51, + 0, + + 17, + 51, + 0, + + 51, + 0, + + 19, + 51, + 0, + + 20, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 26, + 51, + 0, + + 3, + 51, + 0, + + 28, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 34, + 51, + 0, + + 5, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 8, + 51, + 0, + + 9, + 51, + 0, + + 51, + 0, + + 10, + 51, + 0, + + 39, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 15, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 49, + 51, + 0, + + 51, + 0, + + 1, + 51, + 0, + + 51, + 0, + + 29, + 51, + 0, + + 31, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 36, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 42, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 47, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 32, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 35, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 11, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 43, + 51, + 0, + + 44, + 51, + 0, + + 46, + 51, + 0, + + 51, + 0, + + 22, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 4, + 51, + 0, + + 51, + 0, + + 6, + 51, + 0, + + 51, + 0, + + 37, + 51, + 0, + + 40, + 51, + 0, + + 13, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 51, + 0, + + 30, + 51, + 0, + + 51, + 0, + + 7, + 51, + 0, + + 51, + 0, + + 41, + 51, + 0, + + 51, + 0, + + 51, + 0, + + 48, + 51, + 0, + + 50, + 51, + 0, + + 27, + 51, + 0, + + 51, + 0, + + 16, + 51, + 0, + + 18, + 51, + 0, + + 45, + 51, + 0, + + 51, + 0, + + 33, + 51, + 0, + 0}; + # define YYTYPE unsigned char + struct yywork { YYTYPE verify, advance; } yycrank[] = { + 0,0, 0,0, 1,3, 0,0, + 0,0, 0,0, 0,0, 6,31, + 0,0, 0,0, 1,4, 1,5, + 31,0, 0,0, 0,0, 6,31, + 6,0, 0,0, 0,0, 0,0, + 0,0, 0,0, 0,0, 0,0, + 0,0, 0,0, 0,0, 0,0, + 0,0, 0,0, 0,0, 0,0, + 0,0, 0,0, 0,0, 0,0, + 1,6, 0,0, 0,0, 1,7, + 0,0, 6,31, 0,0, 0,0, + 6,31, 1,8, 0,0, 0,0, + 0,0, 1,9, 6,31, 0,0, + 0,0, 0,0, 6,31, 0,0, + 0,0, 0,0, 0,0, 1,10, + 10,33, 0,0, 0,0, 0,0, + 1,11, 0,0, 1,12, 0,0, + 0,0, 6,31, 0,0, 6,31, + 0,0, 0,0, 0,0, 0,0, + 0,0, 0,0, 0,0, 0,0, + 0,0, 2,10, 9,32, 9,32, + 9,32, 9,32, 9,32, 9,32, + 9,32, 9,32, 9,32, 9,32, + 0,0, 0,0, 0,0, 0,0, + 0,0, 0,0, 1,13, 39,69, + 1,14, 1,15, 1,16, 1,17, + 18,48, 1,18, 1,19, 21,51, + 23,53, 1,20, 1,21, 1,22, + 1,23, 1,24, 1,25, 1,26, + 1,27, 1,28, 1,29, 1,30, + 2,13, 17,46, 2,14, 2,15, + 2,16, 2,17, 19,49, 2,18, + 2,19, 20,50, 17,47, 2,20, + 2,21, 2,22, 2,23, 2,24, + 2,25, 2,26, 2,27, 2,28, + 2,29, 2,30, 12,34, 12,34, + 12,34, 12,34, 12,34, 12,34, + 12,34, 12,34, 12,34, 12,34, + 13,35, 13,36, 22,52, 13,37, + 25,56, 26,57, 28,62, 12,34, + 12,34, 12,34, 12,34, 12,34, + 12,34, 12,34, 12,34, 12,34, + 12,34, 12,34, 12,34, 12,34, + 12,34, 12,34, 12,34, 12,34, + 12,34, 12,34, 12,34, 12,34, + 12,34, 12,34, 12,34, 12,34, + 12,34, 24,54, 29,63, 35,66, + 37,67, 12,34, 24,55, 12,34, + 12,34, 12,34, 12,34, 12,34, + 12,34, 12,34, 12,34, 12,34, + 12,34, 12,34, 12,34, 12,34, + 12,34, 12,34, 12,34, 12,34, + 12,34, 12,34, 12,34, 12,34, + 12,34, 12,34, 12,34, 12,34, + 12,34, 14,38, 27,58, 15,42, + 16,44, 27,59, 27,60, 38,68, + 14,39, 30,64, 40,70, 41,71, + 14,40, 15,43, 16,45, 14,41, + 42,72, 27,61, 43,73, 30,65, + 44,74, 45,75, 46,78, 47,79, + 48,80, 49,81, 50,82, 51,83, + 45,76, 52,84, 54,85, 55,86, + 45,77, 56,87, 57,88, 57,89, + 58,91, 59,92, 60,93, 61,94, + 63,96, 64,98, 65,99, 66,101, + 67,102, 65,100, 68,103, 69,104, + 57,90, 70,105, 63,97, 71,106, + 72,107, 73,108, 74,109, 75,110, + 61,95, 76,111, 77,112, 78,113, + 79,114, 80,115, 81,116, 82,118, + 83,119, 84,120, 85,121, 87,122, + 88,123, 89,124, 90,125, 92,126, + 81,117, 93,127, 94,128, 95,129, + 96,130, 97,131, 98,132, 99,133, + 100,134, 101,135, 104,136, 105,137, + 106,138, 107,139, 108,140, 109,141, + 111,142, 112,143, 113,144, 114,145, + 116,146, 119,147, 120,148, 121,149, + 123,150, 124,151, 125,152, 126,153, + 127,154, 128,155, 129,156, 130,157, + 131,158, 132,159, 134,160, 136,161, + 138,162, 139,163, 140,164, 141,165, + 142,166, 143,167, 145,168, 146,169, + 147,170, 148,171, 149,172, 150,173, + 151,174, 152,175, 154,176, 155,177, + 156,178, 158,179, 159,180, 160,181, + 161,182, 162,183, 163,184, 165,185, + 166,186, 168,187, 169,188, 171,189, + 172,190, 173,191, 174,192, 175,193, + 178,194, 179,195, 181,196, 182,197, + 183,198, 185,199, 187,200, 191,201, + 192,202, 193,203, 194,204, 195,205, + 196,206, 197,207, 199,208, 201,209, + 203,210, 204,211, 208,212, 212,213, + 0,0}; + struct yysvf yysvec[] = { + 0, 0, 0, + yycrank+-1, 0, 0, + yycrank+-23, yysvec+1, 0, + yycrank+0, 0, yyvstop+1, + yycrank+0, 0, yyvstop+3, + yycrank+0, 0, yyvstop+6, + yycrank+-6, 0, yyvstop+8, + yycrank+0, 0, yyvstop+11, + yycrank+0, 0, yyvstop+14, + yycrank+34, 0, yyvstop+17, + yycrank+2, 0, yyvstop+20, + yycrank+0, 0, yyvstop+22, + yycrank+94, 0, yyvstop+25, + yycrank+38, yysvec+12, yyvstop+28, + yycrank+120, yysvec+12, yyvstop+31, + yycrank+118, yysvec+12, yyvstop+34, + yycrank+110, yysvec+12, yyvstop+37, + yycrank+13, yysvec+12, yyvstop+40, + yycrank+3, yysvec+12, yyvstop+43, + yycrank+16, yysvec+12, yyvstop+46, + yycrank+18, yysvec+12, yyvstop+49, + yycrank+6, yysvec+12, yyvstop+52, + yycrank+43, yysvec+12, yyvstop+55, + yycrank+6, yysvec+12, yyvstop+58, + yycrank+74, yysvec+12, yyvstop+61, + yycrank+39, yysvec+12, yyvstop+64, + yycrank+56, yysvec+12, yyvstop+67, + yycrank+117, yysvec+12, yyvstop+70, + yycrank+47, yysvec+12, yyvstop+73, + yycrank+76, yysvec+12, yyvstop+76, + yycrank+124, yysvec+12, yyvstop+79, + yycrank+-2, yysvec+6, yyvstop+82, + yycrank+0, yysvec+9, yyvstop+84, + yycrank+0, 0, yyvstop+86, + yycrank+0, yysvec+12, yyvstop+88, + yycrank+73, yysvec+12, yyvstop+90, + yycrank+0, yysvec+12, yyvstop+92, + yycrank+72, yysvec+12, yyvstop+95, + yycrank+108, yysvec+12, yyvstop+97, + yycrank+2, yysvec+12, yyvstop+99, + yycrank+129, yysvec+12, yyvstop+101, + yycrank+117, yysvec+12, yyvstop+103, + yycrank+133, yysvec+12, yyvstop+105, + yycrank+117, yysvec+12, yyvstop+107, + yycrank+119, yysvec+12, yyvstop+109, + yycrank+132, yysvec+12, yyvstop+111, + yycrank+127, yysvec+12, yyvstop+113, + yycrank+129, yysvec+12, yyvstop+115, + yycrank+132, yysvec+12, yyvstop+117, + yycrank+125, yysvec+12, yyvstop+119, + yycrank+132, yysvec+12, yyvstop+121, + yycrank+134, yysvec+12, yyvstop+123, + yycrank+148, yysvec+12, yyvstop+125, + yycrank+0, yysvec+12, yyvstop+127, + yycrank+141, yysvec+12, yyvstop+130, + yycrank+133, yysvec+12, yyvstop+132, + yycrank+144, yysvec+12, yyvstop+134, + yycrank+148, yysvec+12, yyvstop+136, + yycrank+136, yysvec+12, yyvstop+138, + yycrank+142, yysvec+12, yyvstop+140, + yycrank+151, yysvec+12, yyvstop+142, + yycrank+158, yysvec+12, yyvstop+144, + yycrank+0, yysvec+12, yyvstop+146, + yycrank+151, yysvec+12, yyvstop+149, + yycrank+158, yysvec+12, yyvstop+151, + yycrank+153, yysvec+12, yyvstop+153, + yycrank+162, yysvec+12, yyvstop+155, + yycrank+149, yysvec+12, yyvstop+157, + yycrank+146, yysvec+12, yyvstop+159, + yycrank+149, yysvec+12, yyvstop+161, + yycrank+150, yysvec+12, yyvstop+163, + yycrank+152, yysvec+12, yyvstop+165, + yycrank+160, yysvec+12, yyvstop+167, + yycrank+171, yysvec+12, yyvstop+169, + yycrank+161, yysvec+12, yyvstop+171, + yycrank+155, yysvec+12, yyvstop+173, + yycrank+165, yysvec+12, yyvstop+175, + yycrank+173, yysvec+12, yyvstop+177, + yycrank+178, yysvec+12, yyvstop+179, + yycrank+177, yysvec+12, yyvstop+181, + yycrank+165, yysvec+12, yyvstop+183, + yycrank+177, yysvec+12, yyvstop+185, + yycrank+176, yysvec+12, yyvstop+188, + yycrank+182, yysvec+12, yyvstop+190, + yycrank+173, yysvec+12, yyvstop+192, + yycrank+172, yysvec+12, yyvstop+194, + yycrank+0, yysvec+12, yyvstop+196, + yycrank+167, yysvec+12, yyvstop+199, + yycrank+183, yysvec+12, yyvstop+201, + yycrank+180, yysvec+12, yyvstop+204, + yycrank+169, yysvec+12, yyvstop+206, + yycrank+0, yysvec+12, yyvstop+209, + yycrank+173, yysvec+12, yyvstop+212, + yycrank+179, yysvec+12, yyvstop+214, + yycrank+174, yysvec+12, yyvstop+216, + yycrank+174, yysvec+12, yyvstop+218, + yycrank+181, yysvec+12, yyvstop+220, + yycrank+188, yysvec+12, yyvstop+222, + yycrank+178, yysvec+12, yyvstop+224, + yycrank+195, yysvec+12, yyvstop+226, + yycrank+199, yysvec+12, yyvstop+228, + yycrank+176, yysvec+12, yyvstop+230, + yycrank+0, yysvec+12, yyvstop+232, + yycrank+0, yysvec+12, yyvstop+235, + yycrank+201, yysvec+12, yyvstop+238, + yycrank+184, yysvec+12, yyvstop+241, + yycrank+184, yysvec+12, yyvstop+243, + yycrank+204, yysvec+12, yyvstop+245, + yycrank+194, yysvec+12, yyvstop+247, + yycrank+202, yysvec+12, yyvstop+249, + yycrank+0, yysvec+12, yyvstop+252, + yycrank+207, yysvec+12, yyvstop+255, + yycrank+191, yysvec+12, yyvstop+257, + yycrank+190, yysvec+12, yyvstop+259, + yycrank+191, yysvec+12, yyvstop+261, + yycrank+0, yysvec+12, yyvstop+264, + yycrank+205, yysvec+12, yyvstop+267, + yycrank+0, yysvec+12, yyvstop+269, + yycrank+0, yysvec+12, yyvstop+272, + yycrank+208, yysvec+12, yyvstop+275, + yycrank+205, yysvec+12, yyvstop+277, + yycrank+195, yysvec+12, yyvstop+279, + yycrank+0, yysvec+12, yyvstop+281, + yycrank+198, yysvec+12, yyvstop+284, + yycrank+198, yysvec+12, yyvstop+286, + yycrank+200, yysvec+12, yyvstop+288, + yycrank+199, yysvec+12, yyvstop+290, + yycrank+215, yysvec+12, yyvstop+292, + yycrank+212, yysvec+12, yyvstop+294, + yycrank+219, yysvec+12, yyvstop+296, + yycrank+209, yysvec+12, yyvstop+298, + yycrank+217, yysvec+12, yyvstop+300, + yycrank+210, yysvec+12, yyvstop+302, + yycrank+0, yysvec+12, yyvstop+304, + yycrank+206, yysvec+12, yyvstop+307, + yycrank+0, yysvec+12, yyvstop+309, + yycrank+224, yysvec+12, yyvstop+312, + yycrank+0, yysvec+12, yyvstop+314, + yycrank+227, yysvec+12, yyvstop+317, + yycrank+211, yysvec+12, yyvstop+320, + yycrank+225, yysvec+12, yyvstop+322, + yycrank+213, yysvec+12, yyvstop+324, + yycrank+223, yysvec+12, yyvstop+326, + yycrank+219, yysvec+12, yyvstop+328, + yycrank+0, yysvec+12, yyvstop+330, + yycrank+225, yysvec+12, yyvstop+333, + yycrank+230, yysvec+12, yyvstop+335, + yycrank+218, yysvec+12, yyvstop+337, + yycrank+236, yysvec+12, yyvstop+339, + yycrank+233, yysvec+12, yyvstop+341, + yycrank+234, yysvec+12, yyvstop+343, + yycrank+220, yysvec+12, yyvstop+345, + yycrank+227, yysvec+12, yyvstop+347, + yycrank+0, yysvec+12, yyvstop+349, + yycrank+238, yysvec+12, yyvstop+352, + yycrank+240, yysvec+12, yyvstop+354, + yycrank+224, yysvec+12, yyvstop+356, + yycrank+0, yysvec+12, yyvstop+358, + yycrank+231, yysvec+12, yyvstop+361, + yycrank+228, yysvec+12, yyvstop+363, + yycrank+238, yysvec+12, yyvstop+365, + yycrank+228, yysvec+12, yyvstop+367, + yycrank+235, yysvec+12, yyvstop+369, + yycrank+245, yysvec+12, yyvstop+371, + yycrank+0, yysvec+12, yyvstop+373, + yycrank+250, yysvec+12, yyvstop+376, + yycrank+238, yysvec+12, yyvstop+378, + yycrank+0, yysvec+12, yyvstop+380, + yycrank+238, yysvec+12, yyvstop+383, + yycrank+236, yysvec+12, yyvstop+385, + yycrank+0, yysvec+12, yyvstop+387, + yycrank+236, yysvec+12, yyvstop+390, + yycrank+238, yysvec+12, yyvstop+392, + yycrank+243, yysvec+12, yyvstop+394, + yycrank+253, yysvec+12, yyvstop+396, + yycrank+250, yysvec+12, yyvstop+398, + yycrank+0, yysvec+12, yyvstop+400, + yycrank+0, yysvec+12, yyvstop+403, + yycrank+239, yysvec+12, yyvstop+406, + yycrank+256, yysvec+12, yyvstop+409, + yycrank+0, yysvec+12, yyvstop+411, + yycrank+250, yysvec+12, yyvstop+414, + yycrank+258, yysvec+12, yyvstop+416, + yycrank+244, yysvec+12, yyvstop+418, + yycrank+0, yysvec+12, yyvstop+420, + yycrank+245, yysvec+12, yyvstop+423, + yycrank+0, yysvec+12, yyvstop+425, + yycrank+252, yysvec+12, yyvstop+428, + yycrank+0, yysvec+12, yyvstop+430, + yycrank+0, yysvec+12, yyvstop+433, + yycrank+0, yysvec+12, yyvstop+436, + yycrank+264, yysvec+12, yyvstop+439, + yycrank+250, yysvec+12, yyvstop+441, + yycrank+255, yysvec+12, yyvstop+443, + yycrank+252, yysvec+12, yyvstop+445, + yycrank+267, yysvec+12, yyvstop+447, + yycrank+267, yysvec+12, yyvstop+449, + yycrank+255, yysvec+12, yyvstop+451, + yycrank+0, yysvec+12, yyvstop+453, + yycrank+265, yysvec+12, yyvstop+456, + yycrank+0, yysvec+12, yyvstop+458, + yycrank+270, yysvec+12, yyvstop+461, + yycrank+0, yysvec+12, yyvstop+463, + yycrank+269, yysvec+12, yyvstop+466, + yycrank+272, yysvec+12, yyvstop+468, + yycrank+0, yysvec+12, yyvstop+470, + yycrank+0, yysvec+12, yyvstop+473, + yycrank+0, yysvec+12, yyvstop+476, + yycrank+263, yysvec+12, yyvstop+479, + yycrank+0, yysvec+12, yyvstop+481, + yycrank+0, yysvec+12, yyvstop+484, + yycrank+0, yysvec+12, yyvstop+487, + yycrank+265, yysvec+12, yyvstop+490, + yycrank+0, yysvec+12, yyvstop+492, + 0, 0, 0}; + struct yywork *yytop = yycrank+375; + struct yysvf *yybgin = yysvec+1; + char yymatch[] = { + 0, 1, 1, 1, 1, 1, 1, 1, + 1, 9, 10, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 9, 1, 1, 35, 1, 1, 38, 1, + 38, 38, 38, 1, 44, 1, 1, 1, + 48, 48, 48, 48, 48, 48, 48, 48, + 48, 48, 1, 38, 1, 1, 1, 63, + 1, 65, 65, 65, 65, 65, 65, 65, + 65, 65, 65, 65, 65, 65, 65, 65, + 65, 65, 65, 65, 65, 65, 65, 65, + 65, 65, 65, 38, 1, 38, 1, 65, + 1, 65, 65, 65, 65, 65, 65, 65, + 65, 65, 65, 65, 65, 65, 65, 65, + 65, 65, 65, 65, 65, 65, 65, 65, + 65, 65, 65, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 0}; + char yyextra[] = { + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0}; + /* Copyright (c) 1989 AT&T */ + /* All Rights Reserved */ + + /* THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T */ + /* The copyright notice above does not evidence any */ + /* actual or intended publication of such source code. */ + + #pragma ident "@(#)ncform 6.8 95/02/11 SMI" + + int yylineno =1; + # define YYU(x) x + # define NLSTATE yyprevious=YYNEWLINE + struct yysvf *yylstate [YYLMAX], **yylsp, **yyolsp; + char yysbuf[YYLMAX]; + char *yysptr = yysbuf; + int *yyfnd; + extern struct yysvf *yyestate; + int yyprevious = YYNEWLINE; + #if defined(__cplusplus) || defined(__STDC__) + int yylook(void) + #else + yylook() + #endif + { + register struct yysvf *yystate, **lsp; + register struct yywork *yyt; + struct yysvf *yyz; + int yych, yyfirst; + struct yywork *yyr; + # ifdef LEXDEBUG + int debug; + # endif + char *yylastch; + /* start off machines */ + # ifdef LEXDEBUG + debug = 0; + # endif + yyfirst=1; + if (!yymorfg) + yylastch = yytext; + else { + yymorfg=0; + yylastch = yytext+yyleng; + } + for(;;){ + lsp = yylstate; + yyestate = yystate = yybgin; + if (yyprevious==YYNEWLINE) yystate++; + for (;;){ + # ifdef LEXDEBUG + if(debug)fprintf(yyout,"state %d\n",yystate-yysvec-1); + # endif + yyt = yystate->yystoff; + if(yyt == yycrank && !yyfirst){ /* may not be any transitions */ + yyz = yystate->yyother; + if(yyz == 0)break; + if(yyz->yystoff == yycrank)break; + } + #ifndef __cplusplus + *yylastch++ = yych = input(); + #else + *yylastch++ = yych = lex_input(); + #endif + if(yylastch > &yytext[YYLMAX]) { + fprintf(yyout,"Input string too long, limit %d\n",YYLMAX); + exit(1); + } + yyfirst=0; + tryagain: + # ifdef LEXDEBUG + if(debug){ + fprintf(yyout,"char "); + allprint(yych); + putchar('\n'); + } + # endif + yyr = yyt; + if ( (int)yyt > (int)yycrank){ + yyt = yyr + yych; + if (yyt <= yytop && yyt->verify+yysvec == yystate){ + if(yyt->advance+yysvec == YYLERR) /* error transitions */ + {unput(*--yylastch);break;} + *lsp++ = yystate = yyt->advance+yysvec; + if(lsp > &yylstate[YYLMAX]) { + fprintf(yyout,"Input string too long, limit %d\n",YYLMAX); + exit(1); + } + goto contin; + } + } + # ifdef YYOPTIM + else if((int)yyt < (int)yycrank) { /* r < yycrank */ + yyt = yyr = yycrank+(yycrank-yyt); + # ifdef LEXDEBUG + if(debug)fprintf(yyout,"compressed state\n"); + # endif + yyt = yyt + yych; + if(yyt <= yytop && yyt->verify+yysvec == yystate){ + if(yyt->advance+yysvec == YYLERR) /* error transitions */ + {unput(*--yylastch);break;} + *lsp++ = yystate = yyt->advance+yysvec; + if(lsp > &yylstate[YYLMAX]) { + fprintf(yyout,"Input string too long, limit %d\n",YYLMAX); + exit(1); + } + goto contin; + } + yyt = yyr + YYU(yymatch[yych]); + # ifdef LEXDEBUG + if(debug){ + fprintf(yyout,"try fall back character "); + allprint(YYU(yymatch[yych])); + putchar('\n'); + } + # endif + if(yyt <= yytop && yyt->verify+yysvec == yystate){ + if(yyt->advance+yysvec == YYLERR) /* error transition */ + {unput(*--yylastch);break;} + *lsp++ = yystate = yyt->advance+yysvec; + if(lsp > &yylstate[YYLMAX]) { + fprintf(yyout,"Input string too long, limit %d\n",YYLMAX); + exit(1); + } + goto contin; + } + } + if ((yystate = yystate->yyother) && (yyt= yystate->yystoff) != yycrank){ + # ifdef LEXDEBUG + if(debug)fprintf(yyout,"fall back to state %d\n",yystate-yysvec-1); + # endif + goto tryagain; + } + # endif + else + {unput(*--yylastch);break;} + contin: + # ifdef LEXDEBUG + if(debug){ + fprintf(yyout,"state %d char ",yystate-yysvec-1); + allprint(yych); + putchar('\n'); + } + # endif + ; + } + # ifdef LEXDEBUG + if(debug){ + fprintf(yyout,"stopped at %d with ",*(lsp-1)-yysvec-1); + allprint(yych); + putchar('\n'); + } + # endif + while (lsp-- > yylstate){ + *yylastch-- = 0; + if (*lsp != 0 && (yyfnd= (*lsp)->yystops) && *yyfnd > 0){ + yyolsp = lsp; + if(yyextra[*yyfnd]){ /* must backup */ + while(yyback((*lsp)->yystops,-*yyfnd) != 1 && lsp > yylstate){ + lsp--; + unput(*yylastch--); + } + } + yyprevious = YYU(*yylastch); + yylsp = lsp; + yyleng = yylastch-yytext+1; + yytext[yyleng] = 0; + # ifdef LEXDEBUG + if(debug){ + fprintf(yyout,"\nmatch "); + sprint(yytext); + fprintf(yyout," action %d\n",*yyfnd); + } + # endif + return(*yyfnd++); + } + unput(*yylastch); + } + if (yytext[0] == 0 /* && feof(yyin) */) + { + yysptr=yysbuf; + return(0); + } + #ifndef __cplusplus + yyprevious = yytext[0] = input(); + if (yyprevious>0) + output(yyprevious); + #else + yyprevious = yytext[0] = lex_input(); + if (yyprevious>0) + lex_output(yyprevious); + #endif + yylastch=yytext; + # ifdef LEXDEBUG + if(debug)putchar('\n'); + # endif + } + } + #if defined(__cplusplus) || defined(__STDC__) + int yyback(int *p, int m) + #else + yyback(p, m) + int *p; + #endif + { + if (p==0) return(0); + while (*p) { + if (*p++ == m) + return(1); + } + return(0); + } + /* the following are only used in the lex library */ + #if defined(__cplusplus) || defined(__STDC__) + int yyinput(void) + #else + yyinput() + #endif + { + #ifndef __cplusplus + return(input()); + #else + return(lex_input()); + #endif + } + #if defined(__cplusplus) || defined(__STDC__) + void yyoutput(int c) + #else + yyoutput(c) + int c; + #endif + { + #ifndef __cplusplus + output(c); + #else + lex_output(c); + #endif + } + #if defined(__cplusplus) || defined(__STDC__) + void yyunput(int c) + #else + yyunput(c) + int c; + #endif + { + unput(c); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdlex.l.in diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdlex.l.in:1.1 *** /dev/null Tue Oct 5 14:08:40 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/cdlex.l.in Tue Oct 5 14:08:26 2004 *************** *** 0 **** --- 1,75 ---- + %{ + /* Lexical analyzer description for ANSI and C++ cdecl. */ + /* The output of this file is included */ + /* into the C file cdecl.c. */ + char cdlexsccsid[] = "@(#)cdlex.l 2.2 3/30/88"; + %} + + N [0-9] + A [A-Z_a-z] + AN [0-9A-Z_a-z] + + %% + array return ARRAY; + as return AS; + cast return CAST; + declare return DECLARE; + exit return 0; + explain return EXPLAIN; + function return FUNCTION; + func return FUNCTION; + help return HELP; + into return INTO; + member return MEMBER; + of return OF; + pointer return POINTER; + ptr return POINTER; + quit return 0; + reference return REFERENCE; + ref return REFERENCE; + returning return RETURNING; + ret return RETURNING; + set return SET; + to return TO; + vector return ARRAY; + :: return DOUBLECOLON; + [?] return HELP; + [,] return COMMA; + + auto { yylval.dynstr = ds(yytext); return AUTO; } + character { yylval.dynstr = ds("char"); return CHAR; } + char { yylval.dynstr = ds(yytext); return CHAR; } + class { yylval.dynstr = ds(yytext); return CLASS; } + constant { yylval.dynstr = ds("const"); return CONSTVOLATILE; } + const { yylval.dynstr = ds(yytext); return CONSTVOLATILE; } + double { yylval.dynstr = ds(yytext); return DOUBLE; } + enumeration { yylval.dynstr = ds("enum"); return ENUM; } + enum { yylval.dynstr = ds(yytext); return ENUM; } + extern { yylval.dynstr = ds(yytext); return EXTERN; } + float { yylval.dynstr = ds(yytext); return FLOAT; } + integer { yylval.dynstr = ds("int"); return INT; } + int { yylval.dynstr = ds(yytext); return INT; } + long { yylval.dynstr = ds(yytext); return LONG; } + noalias { yylval.dynstr = ds(yytext); return CONSTVOLATILE; } + register { yylval.dynstr = ds(yytext); return REGISTER; } + short { yylval.dynstr = ds(yytext); return SHORT; } + signed { yylval.dynstr = ds(yytext); return SIGNED; } + static { yylval.dynstr = ds(yytext); return STATIC; } + structure { yylval.dynstr = ds("struct"); return STRUCT; } + struct { yylval.dynstr = ds(yytext); return STRUCT; } + union { yylval.dynstr = ds(yytext); return UNION; } + unsigned { yylval.dynstr = ds(yytext); return UNSIGNED; } + void { yylval.dynstr = ds(yytext); return VOID; } + volatile { yylval.dynstr = ds(yytext); return CONSTVOLATILE; } + + {A}{AN}* { yylval.dynstr = ds(yytext); return NAME; } + {N}+ { yylval.dynstr = ds(yytext); return NUMBER; } + + [#].* ; + [\t ] ; + [&*[\]();\n] return *yytext; + . { + (void) printf("bad character '%s'\n",visible(*yytext)); + return *yytext; + } + %% Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/testset diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/testset:1.1 *** /dev/null Tue Oct 5 14:08:40 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/cdecl/testset Tue Oct 5 14:08:26 2004 *************** *** 0 **** --- 1,71 ---- + help + set options + # test some declarations + declare x as ptr to character + declare x as func(w as ptr to char, y as int) ret ptr to int + declare x as func(ptr to char) ret ptr to int + declare x as func(int) ret ptr to int + declare x as func(ptr to char, int) ret ptr to int + declare x as function (args) returning pointer to int + # test some explain functions + explain char *x + explain int *x() + explain int *x(args) + explain int *x(char *) + explain int *x(char *, int ) + explain int *x(char *, int, float) + explain int *x(int ) + # test some casts + cast x into ptr to char + cast x into ptr to func ret int + cast x into ptr to func() ret int + cast x into ptr to func(args) ret int + cast x into ptr to func(x as ptr to char, y as int) ret int + cast x into ptr to func(ptr to char) ret int + cast x into ptr to func(ptr to char, int) ret int + cast x into ptr to func(ptr to char, int, float) ret int + # test explaining some casts + explain (char *)x + explain (int (*)())x + explain (int (*)(char *))x + explain (int (*)(char *, int))x + explain (int (*)(char *, int, float))x + help + set options + # test some declarations + declare x as ptr to character + declare x as reference to character + declare foo as pointer to member of class X int + declare foo as pointer to member of class X function (arg1, arg2) returning pointer to class Y + declare x as func(w as ptr to char, y as int) ret ptr to int + declare x as func(ptr to char) ret ptr to int + declare x as func(int) ret ptr to int + declare x as func(ptr to char, int) ret ptr to int + declare x as function (args) returning pointer to int + # test some explain functions + explain char *x + explain int X::*foo + explain class Y *(X::*foo)(arg1, arg2) + explain int *x() + explain int *x(args) + explain int *x(char *) + explain int *x(char *, int ) + explain int *x(char *, int, float) + explain int *x(int ) + # test some casts + cast x into ptr to char + cast x into ptr to member of class X int + cast x into ptr to func ret int + cast x into ptr to func() ret int + cast x into ptr to func(args) ret int + cast x into ptr to func(x as ptr to char, y as int) ret int + cast x into ptr to func(ptr to char) ret int + cast x into ptr to func(ptr to char, int) ret int + cast x into ptr to func(ptr to char, int, float) ret int + # test explaining some casts + explain (char *)x + explain (int X::*)x + explain (int (*)())x + explain (int (*)(char *))x + explain (int (*)(char *, int))x + explain (int (*)(char *, int, float))x From lattner at cs.uiuc.edu Tue Oct 5 14:24:09 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 14:24:09 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/ Message-ID: <200410051924.OAA23993@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 14:24:17 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 14:24:17 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/Makefile emitter.c error.c global.h init.c lexer.c main.c parser.c symbol.c Message-ID: <200410051924.OAA24015@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler: Makefile added (r1.1) emitter.c added (r1.1) error.c added (r1.1) global.h added (r1.1) init.c added (r1.1) lexer.c added (r1.1) main.c added (r1.1) parser.c added (r1.1) symbol.c added (r1.1) --- Log message: New benchmark, also missing an input --- Diffs of the changes: (+2374 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/Makefile:1.1 *** /dev/null Tue Oct 5 14:24:17 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/Makefile Tue Oct 5 14:24:06 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = compiler + #STDIN_FILENAME = $(SourceDir)/testset + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/emitter.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/emitter.c:1.1 *** /dev/null Tue Oct 5 14:24:17 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/emitter.c Tue Oct 5 14:24:06 2004 *************** *** 0 **** --- 1,171 ---- + /**** emitter.c *******************************************************/ + + #include "global.h" + + void emit(int t, int tval, float rval) /* generates output */ + { + if (ErrorFlag) + return; + + ++NumberC; + if (NumberC >= 8) + { + printf("\n"); + NumberC = 0; + } /* end if NumberC */ + + switch(t) { + case RADD: + printf("RADD, "); + break; + case ADD: + printf("ADD, "); + break; + case RSUB: + printf("RSUB, "); + break; + case SUB: + printf("SUB, "); + break; + case RMUL: + printf("RMUL, "); + break; + case MUL: + printf("MUL, "); + break; + case RDIV: + printf("RDIV, "); + break; + case DIV: + printf("DIV, "); + break; + case PUSH_LOC_VAR_ADDR: + printf("'%s#%d, ", LocalTable[tval].lexptr, Scope); + break; + case PUSH_GLO_VAR_ADDR: + printf("'%s#0, ", GlobalTable[tval].lexptr); + break; + case WRITEI: + printf("WRITEI, "); + break; + case WRITEF: + printf("WRITER, "); + break; + case WRITELN: + printf("NEWLINE, "); + break; + case STORE: + printf("ST, "); + break; + case IST: + printf("IST, "); + break; + case STH: + printf("STH, "); + break; + case VAL: + printf("VAL, "); + break; + case VALB: + printf("VALB, "); + break; + case PUSH_GLO_VAR_VALUE: + printf("@%s#0, ",GlobalTable[tval].lexptr); + break; + case PUSH_LOC_VAR_VALUE: + printf(">%s#%d, ", LocalTable[tval].lexptr, Scope); + break; + case READ: + printf("READ, "); + break; + case NUM: + printf("%d, ", tval); + break; + case RNUM: + printf("%16.4e, ", rval); + break; + case GLO_DECL: /* here tval is a subscript to the symbol table */ + printf("%s#0 = %d, ", GlobalTable[tval].lexptr, DecCount); + break; + case LOC_DECL: + printf("%s#%d = %d, ", LocalTable[tval].lexptr, Scope, offset); + break; + case NEG: + printf("NEG, "); + break; + case RNEG: + printf("RNEG, "); + break; + case INT: + printf("FIX, "); + break; + case FLOAT: + printf("FLOAT, "); + break; + case POP: + printf("POP, "); + break; + case LABEL_CODE: + printf("$%d: ", tval); + break; + case PUSH_CODE_LABEL: + printf("$%d, ", tval); + break; + case COMP: + printf("COMP, "); + break; + case SWAP: + printf("SWAP, "); + break; + case BEQ: + printf("BEQ, "); + break; + case BNE: + printf("BNE, "); + break; + case B: + printf("B, "); + break; + case STHB: + printf("STHB, "); + break; + case LABEL_FUNC: + printf("%s: ", GlobalTable[tval].lexptr); + break; + case ISTB: + printf("ISTB, "); + break; + case STORE_RA: + printf("RA%s = 0, ", GlobalTable[tval].lexptr); + printf("'RA%s, ", GlobalTable[tval].lexptr); + printf("istb, "); + break; + case SAVE_FRAMESIZE: + printf("frame%s = %d, ", GlobalTable[tval].lexptr, offset); + break; + case PUSH_FRAMESIZE: + printf("'frame%s, ", GlobalTable[tval].lexptr); + break; + case IB: + printf("IB, "); + break; + case DB: + printf("DB, "); + break; + case PUSH_RA: + printf(">RA%s, ", GlobalTable[tval].lexptr); + break; + case BEGIN: + printf("\n%%%d, START: $3, sb, $2, $1, b,\n", DecCount); + NumberC = 0; + break; + case END: + printf("\n$2: STOP, $3: ->START.\n"); + break; + case NOTDEC: + printf("\n Function %s called but not parsed.\n",GlobalTable[tval].lexptr); + break; + default: + printf("token %d, tval %d, rval %f\n", t, tval, rval); + } + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/error.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/error.c:1.1 *** /dev/null Tue Oct 5 14:24:17 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/error.c Tue Oct 5 14:24:06 2004 *************** *** 0 **** --- 1,39 ---- + /**** error.c **********************************************************/ + + #include "global.h" + extern void match(int t); + + void error(char *m) /* generates all error messages */ + { + ErrorFlag = 1; + printf("\nERROR: line %d: %s \n", lineno, m); + + if (lookahead == DONE) + return; + + printf("Skipping: "); + while ((lookahead != ';') && (lookahead != EOF)) + { + lookahead = getc(stdin); + if (lookahead == '\n') + ++lineno; + if (lookahead != EOF) + printf ("%c", lookahead); + } + + if (lookahead == EOF) + { + lookahead = DONE; + return; + } + else + match(';'); + + printf("\n continuing parsing...\n"); + return; + } + + + + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/global.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/global.h:1.1 *** /dev/null Tue Oct 5 14:24:17 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/global.h Tue Oct 5 14:24:06 2004 *************** *** 0 **** --- 1,133 ---- + + /****** global.h ********************************************************/ + + #include + #include + /* + extern char *strcpy(); + extern int strcmp(); + */ + + #define STRMAX 999 /* size of lexemes array */ + #define SYMMAX 100 /* size of symtable */ + + #define BSIZE 128 /* buffer size */ + #define NONE -1 + #define EOS '\0' /* END OF STRING */ + + #define NUM 256 /* token for integers */ + #define ID 259 /* token for identifiers */ + #define DONE 260 /* token for end of file */ + + #define RNUM 2001 /* token for real numbers */ + #define INT 2002 /* token for the string "int" */ + #define FLOAT 2003 /* token for the string "float" */ + #define POP 2004 /* token for poping to a labeled location */ + #define PUSH_LABEL 2005 /* token for outputing push from labeled loc. */ + #define ARRAY 2006 /* token for an array referance */ + #define WHILE 2007 /* token for the keyword while */ + #define IF 2008 /* token for the keyword if */ + #define READ 2009 /* token for the keyword read */ + #define WRITE 2010 /* token for the keyword write */ + #define WRITELN 2011 /* token for the keyword writeln */ + #define EQUAL 2012 /* token for == */ + #define NEQUAL 2013 /* token for != */ + #define LABEL_CODE 2014 /* emitter code to label an assemble stmt */ + #define PUSH_CODE_LABEL 2015 /* emitter code to push code labels */ + #define COMP 2016 /* emitter code for comp opcode */ + #define BEQ 2017 /* emitter code for BEQ */ + #define B 2018 /* emitter code for B */ + #define STORE 2020 /* emitter code to output ST */ + #define STH 2022 /* emitter code for STH command */ + #define VAL 2023 /* emitter code for VAL command */ + #define ELSE 2024 /* token for keyword else */ + #define BNE 2025 /* emitter code for BNE command */ + #define BEGIN 2026 /* emitter code: print special char at start prg*/ + #define END 2027 /* emitter code: print special char at end prog */ + #define IST 2028 /* emitter code for IST instruction */ + #define ADD 2029 /* emitter code for ADD */ + #define RADD 2030 /* emitter code for RADD */ + #define SUB 2031 /* emitter code for SUB */ + #define RSUB 2032 /* emitter code for RSUB */ + #define MUL 2033 /* emitter code for MUL */ + #define RMUL 2034 /* emitter code for RMUL */ + #define DIV 2035 /* emitter code for DIV */ + #define RDIV 2036 /* emitter code for RDIV */ + #define SWAP 2037 /* emitter code for SWAP */ + #define NEG 2038 /* emitter code for NEG */ + #define RNEG 2039 /* emitter code for RNEG */ + #define FIX 2040 /* emitter code for FIX */ + #define PARAM 2041 /* code for parameters in symbol tables */ + #define RETURN 2042 /* token for return keyword */ + #define READF 2043 /* token for readf() */ + #define READI 2044 /* token for readi() */ + #define WRITEF 2045 /* token for writef() */ + #define WRITEI 2046 /* token for writei() */ + #define LOC_DECL 2047 /* emitter code for a local declaration */ + #define GLO_DECL 2048 /* emitter code for a global declaration */ + #define PUSH_LOC_VAR_ADDR 2049 /* emitter code to push the address of a + local variable */ + #define PUSH_GLO_VAR_ADDR 2050 /* emitter code to push the address of a + global varialbe */ + #define PUSH_LOC_VAR_VALUE 2051 /* emitter code to push value stored + in a local variable */ + #define PUSH_GLO_VAR_VALUE 2052 /* emitter code to push value stored + in a global variable */ + #define STHB 2053 /* emitter code for STHB */ + #define LABEL_FUNC 2054 /* emitter code to insert function name in code */ + #define ISTB 2055 /* emitter code for ISTB instruction */ + #define STORE_RA 2056 /* emitter code to store return address */ + #define SAVE_FRAMESIZE 2057 /* emitter code to save frame size */ + #define PUSH_RA 2058 /* emitter code to push the return address */ + #define PUSH_FRAMESIZE 2059 /* emitter code for pushing the frame size */ + #define IB 2060 /* emitter code for ib */ + #define DB 2061 /* emitter code for db */ + #define NOTDEC 2062 /* emitter code for funtion not parsed */ + #define VALB 2063 /* emitter code for VALB */ + + int lookahead; /* token code number */ + int tokenval; /* value of token attribute */ + float ftokenval; /* global for float RNUM attribute */ + int FloatFlag; /* used as boolean, 1 if we doing float calcs. */ + int ErrorFlag; /* 1 if an error has occured, 0 otherwise */ + int DecCount; /* keeps track of memeory locations */ + int offset; /* offset within an activation record, local var*/ + int lineno; /* the current line number */ + int LabelCounter; /* used to create new labels for the mach. code */ + int NumberC; /* keeps track of number of commands emitted */ + char lexbuf[BSIZE]; /* stores lexeme to be inserted into symtable */ + int LocalIndex; /* value returned from lookup in loctable */ + int GlobalIndex; /* value returned from lookup to glotable */ + int NextLookahead; /* the next token of the input */ + int NextTokenval; /* the tokenval associated with the next token */ + float NextFtokenval; /* the ftokenval associated with the next token */ + int PreviousLookahead; /* the token that was last matched */ + int PreviousTokenval; /* tokenval associated with the previous token*/ + float PreviousFtokenval; /* ftokenval associated with the previous token*/ + int Scope; /* the label assoc. with the current function + to be used in the creation of unique labels */ + int ReturnLabel; /* stores the label to jump out of a function + if a return is encountered */ + int CallReturnAddr; /* return address of a function call */ + int FuncNameIndex; /* stores the index of the current function + name*/ + int ArrayParsed; /* flag set to 1 if PushArrayCellAddr() called + while lookahead is ARRAY */ + + struct entry { /* form of symbol table entry */ + char *lexptr; /* ptr to lexeme */ + int token; /* token: ID or ARRAY */ + int type; /* type of entry: INT or FLOAT */ + int size; /* size of entry: 1 for INT or FLOAT, + larger for arrays */ + int function; /* non-zero if is a function. + field is > 0 if function called but not parsed, + field is < 0 if function body has been parsed*/ + int functionlabel; /* stores the machine code label associated + with the function */ + }; + + + struct entry GlobalTable[SYMMAX]; /* Global symbol table */ + struct entry LocalTable[SYMMAX]; /* Local symbol table */ + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/init.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/init.c:1.1 *** /dev/null Tue Oct 5 14:24:17 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/init.c Tue Oct 5 14:24:06 2004 *************** *** 0 **** --- 1,42 ---- + /**** init.c ********************************************************/ + + #include "global.h" + extern int GlobalInsert(char s[], int tok, int type, int size, int function, + int functionlabel); + + /* contains all keywords to be added to the symbol table */ + struct entry keywords[] = { + { "int", INT, 0, 0, 0, 0 }, + { "float", FLOAT, 0, 0, 0, 0 }, + { "while", WHILE, 0, 0, 0, 0 }, + { "if", IF, 0, 0, 0, 0 }, + { "else", ELSE, 0, 0, 0, 0 }, + { "read", READ, 0, 0, 0, 0 }, + { "write", WRITE, 0, 0, 0, 0 }, + { "writeln", WRITELN, 0, 0, 0, 0 }, + { "return", RETURN, 0, 0, 0, 0 }, + { "readf", READF, 0, 0, 0, 0 }, + { "readi", READI, 0, 0, 0, 0 }, + { "writef", WRITEF, 0, 0, 0, 0 }, + { "writei", WRITEI, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0 } + }; + + void init(void) + { + /* loads keywords into symtable */ + struct entry *p; + for (p = keywords; p->token; p++) + (void) GlobalInsert(p->lexptr, p->token, p->type, p->size, 0, 0); + + lineno = 1; + LabelCounter = 1; + DecCount = 2; + ErrorFlag = 0; + NumberC = 0; + } + + + + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/lexer.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/lexer.c:1.1 *** /dev/null Tue Oct 5 14:24:17 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/lexer.c Tue Oct 5 14:24:06 2004 *************** *** 0 **** --- 1,231 ---- + /**** lexer.c ***************************************************************/ + + + # include "global.h" + extern int Number(int t); + extern int Indentifier(int t); + extern int Equal(int t); + extern int Nequal(int t); + extern void error(char *m); + extern int LocalLookup(char s[]); + extern int GlobalLookup(char s[]); + + int lexan(void) + { + int t; /* temp to check next char in input */ + + while (1) + { + t = getc(stdin); + if (t == ' ' || t == '\t') + ; /* strip out white space */ + + else if (t == '\n') + ++lineno; + + else if (isdigit(t) || t == '.' ) + return (Number(t)); + + else if ( isalpha(t) || t == '_') + return(Indentifier(t)); + + else if (t == '=') + return (Equal(t) ); + + else if (t == '!') + return (Nequal(t) ); + + else if (t == EOF) + return(DONE); + + else + { + NextTokenval = NONE; + return(t); + } /* end else */ + } /* end while (1) */ + } /* end lexan */ + + /* ======================================================================= */ + + int Indentifier(int t) + { + int b = 0; /* used as a index to lexbuf */ + + if (t == '_') + { + lexbuf[b] = t; + ++b; + t = getc(stdin); + + if (t == '_') + { + error("Indentifier cannot begin with a double underscore"); + return(lookahead); + } /* end if (t == '_') */ + } /* end if (t == '_') */ + + if (isalpha(t)) + { + lexbuf[b] = t; + ++b; + t = getc(stdin); + } /* end if (isalpha(t)) */ + else + { + error("improperly formed indentifier"); + return(lookahead); + } /* end else */ + + while (isalpha(t) || isdigit(t) || t == '_') + { + lexbuf[b] = t; + ++b; + t = getc(stdin); + } /* end while */ + + (void) ungetc (t, stdin); + lexbuf[b] = EOS; + + LocalIndex = LocalLookup(lexbuf); + GlobalIndex = GlobalLookup(lexbuf); + + if (LocalIndex) + return(LocalTable[LocalIndex].token); + else if (GlobalIndex) + return (GlobalTable[GlobalIndex].token); + else + return(ID); + } + + /* ======================================================================== */ + + int Equal(int t) + { + t = getc(stdin); + if (t == '=') + return(EQUAL); + else + { + (void) ungetc(t,stdin); + NextTokenval = NONE; + return('='); + } /* end else */ + } /* end Equal function */ + + /* ======================================================================= */ + + int Nequal(int t) + { + t = getc(stdin); + if (t == '=') + return(NEQUAL); + else + { + (void) ungetc(t,stdin); + NextTokenval = NONE; + return('!'); + } /* end else */ + } /* end function Nequal */ + + /* ====================================================================== */ + + int Number(int t) + { + int DecimalAsInt; /* temp holder of the number */ + int Exponent; + int NumOfZeros; + + NextFtokenval = 0.0; + NextTokenval = 0; + + /* get interger portion of float or the whole integer */ + if (isdigit (t)) + { + (void) ungetc(t, stdin); + scanf("%d", &NextTokenval); + t = getc(stdin); + if ((t != '.') && (t != 'e') && (t != 'E')) + { + (void) ungetc(t, stdin); + return (NUM); + } + } /* end if t is digit */ + + /* NextTokenval set at this point or NUM has been returned */ + if (t == '.') + { + t = getc(stdin); + NumOfZeros = 0; + + /* + counts the number of zeros left of decimal and right of the + first non-zero digit. + */ + while (t == '0') + { + ++NumOfZeros; + t = getc(stdin); + } /* end while t == 0 */ + + /* reads the number after any leading zeros */ + if (isdigit (t)) + { + (void) ungetc(t, stdin); + scanf("%d", &DecimalAsInt); + NextFtokenval = (float) DecimalAsInt; + + /* converts the decimal characters into a decimal of the number */ + while (NextFtokenval >= 1.0) + { + NextFtokenval /= 10; + } /* end NextFtokenval > 1 */ + if (NumOfZeros > 0) + { + while (NumOfZeros > 0) + { + NextFtokenval /= 10; + --NumOfZeros; + } /* end num of zeros > 0 */ + } /* end if num of zeros > 0 */ + t = getc(stdin); /* not needed here, but used later */ + } /* end if t is digit */ + } /* end if t == . */ + + /* tokenval and ftokenval set if needed, otherwise still zero */ + NextFtokenval += NextTokenval; + if ((t == 'e') || (t == 'E')) + { + t = getc(stdin); + if ((t == '+') || (t == '-') || (isdigit (t))) + { + (void) ungetc(t, stdin); + scanf("%d", &Exponent); + t = getc(stdin); /* used for error checking, but also used later */ + if (t == '.') + { + error("Exponents must be integer values"); + return(lookahead); + } /* end if exponent value is a float */ + if (Exponent > 0) + { + while (Exponent > 0) + { + NextFtokenval *= 10; + --Exponent; + } /* end while */ + } /* end if Exponent > 0 */ + else + { + while (Exponent < 0) + { + NextFtokenval /= 10; + ++Exponent; + } /* end while */ + } /* end else Exponent > 0 */ + } /* end if t is +, -, or a digit */ + } /* if t == e or t == E */ + (void) ungetc(t, stdin); + return(RNUM); + } /* end isdigit or . */ + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/main.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/main.c:1.1 *** /dev/null Tue Oct 5 14:24:17 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/main.c Tue Oct 5 14:24:06 2004 *************** *** 0 **** --- 1,13 ---- + /**** main.c *********************************************************/ + + #include "global.h" + + extern void init(void); + extern void parse(void); + + int main(void) + { + init(); + parse(); + return 0; /* successful termination */ + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/parser.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/parser.c:1.1 *** /dev/null Tue Oct 5 14:24:17 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/parser.c Tue Oct 5 14:24:06 2004 *************** *** 0 **** --- 1,1543 ---- + /**** parser.c ***************************************************/ + + #include "global.h" + + extern void emit(int t, int tval, float rval); + extern void error(char *m); + extern int lexan(void); + extern int GlobalInsert(char s[], int tok, int type, int size, int function, + int functionlabel); + extern void CheckMain(void); + extern void AllBodsParsed(void); + extern void LocalReset(void); + extern int LocalInsert(char s[], int tok, int type, int size,int function, + int functionlabel); + extern void ParamInt(void); + + int term(void); + void match(int t); + int expr(void); + void PushArrayCellAddr(void); + void DeclOrF(void); + void GlobalScopeAndInsert(int type); + void GlobalVarList(int type); + void exprTest(void); + void exprAssg(void); + void parseAStmt(void); + void parse(void); + int factor(void); + void ExprList(void); + void FunctionList(void); + void FunctionDef(int type); + void MoreParams(void); + void ParamList(void); + void DecList(void); + void VarList(int type); + void FstmtList(void); + + int term(void) + { + int t; /* temporary holder of tokens */ + int leftExpr, rightExpr; + + leftExpr = factor(); + if (ErrorFlag) + return -99; + while(lookahead == '*' || lookahead == '/') + { + t = lookahead; + match(lookahead); + if (ErrorFlag) + return -99; + rightExpr = factor(); + if (ErrorFlag) + return -99; + if (leftExpr == rightExpr) + { + if (leftExpr) + { + if (t == '*') + emit(RMUL, 0, 0.0); + else + emit(RDIV, 0, 0.0); + leftExpr = 1; + } + else + { + if (t == '*') + emit(MUL, 0, 0.0); + else + emit(DIV, 0, 0.0); + leftExpr = 0; + } + } + else + { + if (leftExpr) + { + emit(FLOAT, 0, 0.0); + if (t == '*') + emit(RMUL, 0, 0.0); + else + emit(RDIV, 0, 0.0); + } + else + { + emit(NUM, 1, 0.0); + emit(IST, 0, 0.0); + emit(FLOAT, 0, 0.0); + emit(NUM, 1, 0.0); + emit(VAL, 0, 0.0); + if (t == '*') + emit(RMUL, 0, 0.0); + else + emit(RDIV, 0, 0.0); + } + leftExpr = 1; + } /* end else leftExpr == rightExpr */ + } + if (FloatFlag) + return(1); + else + return (leftExpr); + } + /* ========================================================================= */ + + void match(int t) /* verify that t was the last token, then get next token */ + /* token to verify as last found */ + { + if (lookahead == t) + { + PreviousLookahead = lookahead; + PreviousTokenval = tokenval; + PreviousFtokenval = ftokenval; + + lookahead = NextLookahead; + tokenval = NextTokenval; + ftokenval = NextFtokenval; + + if (NextLookahead != DONE) + NextLookahead = lexan(); + } + else + { + switch (lookahead) + { + case WHILE: + case IF: + error("Missing ; at end of previous statement"); + break; + } + if (ErrorFlag) + return; + switch (t) + { + case ')': + error("Missing right parenthesis or illegal operator"); + break; + default: + printf("\n In default of match lookahead = %d",lookahead); + error("syntax error"); + break; + } /* end switch */ + } /* else */ + } + + /* ------------------------------------------------------------------- */ + + int expr(void) + { + int t; /* temporary holder of tokens */ + int leftExpr, rightExpr; + + leftExpr = term(); + if (ErrorFlag) + return -99; + while(lookahead == '+' || lookahead == '-') + { + t = lookahead; + match(lookahead); + if (ErrorFlag) + return -99; + rightExpr = term(); + if (ErrorFlag) + return -99; + if (leftExpr == rightExpr) + { + if (leftExpr) + { + if (t == '+') + emit(RADD, 0, 0.0); + else + emit(RSUB, 0, 0.0); + leftExpr = 1; + } + else + { + if (t == '+') + emit(ADD, 0, 0.0); + else + emit(SUB, 0, 0.0); + leftExpr = 0; + } + } + else + { + if (leftExpr) + { + emit(FLOAT, 0, 0.0); + if (t == '+') + emit(RADD, 0, 0.0); + else + emit(RSUB, 0, 0.0); + } + else + { + emit(NUM, 1, 0.0); + emit(IST, 0, 0.0); + emit(FLOAT, 0, 0.0); + emit(NUM, 1, 0.0); + emit(VAL, 0, 0.0); + if (t == '+') + emit(RADD, 0, 0.0); + else + emit(RSUB, 0, 0.0); + } + leftExpr = 1; + } /* end else leftExpr == rightExpr */ + } + if (FloatFlag) + return(1); + else + return(leftExpr); + + } + /* ========================================================================= */ + + + + void PushArrayCellAddr(void) /* calculate address of array cell on stack */ + { + int tempTokenval; + + if ( !(ArrayParsed)) + { + ArrayParsed = 1; + tempTokenval = tokenval; + if (LocalIndex) + emit(PUSH_LOC_VAR_ADDR, LocalIndex, 0.0); + else if (GlobalIndex) + emit(PUSH_GLO_VAR_ADDR, GlobalIndex, 0.0); + else + { + error("Compiler error, array lexeme not found in any table"); + return; + } + match(ARRAY); + if (ErrorFlag) + return; + match('['); + if (ErrorFlag) + return; + FloatFlag = 0; + FloatFlag = expr(); + if (ErrorFlag) + return; + if (lookahead != ']') + { + error("Missing ']'"); + return; + } + if (FloatFlag) + { + error("Array index must be an integer value"); + return; + } + emit(ADD, 0, 0.0); + lookahead = ARRAY; + tokenval = tempTokenval; + } /* end if !ArrayParsed */ + else + ArrayParsed = 0; + } /* end PushArrayCellAddr */ + + /* ============================================================= */ + + void DeclOrF(void) + { + int type; /* stores type to call other functions with */ + int temp; + + Scope = 0; /* set scope to zero to mean global variables */ + + while(1) + { + if (lookahead == ID) + { + emit(BEGIN, 0, 0.0); + LabelCounter = 4; /* first 3 label used by emit BEGIN */ + /* insert an implicit call to main into the symbol tabel */ + temp = GlobalInsert ("main",ID,INT,0,1,1); + if (ErrorFlag) + return; + if (strcmp("main", lexbuf) == 0) + GlobalIndex = temp; + FunctionDef (INT); + if (ErrorFlag) + return; + return; + } + else if (lookahead == INT) + { + match (INT); + if (ErrorFlag) + return; + } + else + { + match (FLOAT); + if (ErrorFlag) + return; + } + + if (NextLookahead == '(') + { + emit(BEGIN, 0, 0.0); + LabelCounter = 4; /* first 3 labels used by emit BAGIN */ + /* insert an implicit call to main into the symbol tabel */ + temp = GlobalInsert ("main",ID,INT,0,1,1); + if (ErrorFlag) + return; + if (strcmp("main", lexbuf) == 0) + GlobalIndex = temp; + FunctionDef(PreviousLookahead); + if (ErrorFlag) + return; + return; + } + else + { + type = PreviousLookahead; + GlobalScopeAndInsert (type); + if (ErrorFlag) + return; + GlobalVarList (type); + if (ErrorFlag) + return; + match(';'); + if (ErrorFlag) + return; + } /* end if != '(' */ + } /* end while(1) */ + } /* end DeclOrF */ + + /* ============================================================= */ + + void GlobalScopeAndInsert(int type) + { + int tempGlobalIndex; + + if (LocalIndex) + { + error("Compiler error! global lexeme found in local symbol table"); + return; + } /* end LocalIndex */ + else if (GlobalIndex) + { + if (GlobalTable[GlobalIndex].function) + { + error("Attempting to define a function name as an identifier"); + return; + } /* end if */ + + else + { + error("Attempting to define a global variable twice"); + return; + } /* end else */ + } /* end else ifGlobalIndex */ + else + { + if (NextLookahead == '[') + { + tempGlobalIndex = GlobalIndex = GlobalInsert(lexbuf, ARRAY, type,0,0,0); + if (ErrorFlag) + return; + match(ID); + if (ErrorFlag) + return; + match('['); + if (ErrorFlag) + return; + if (lookahead == NUM) + { + GlobalTable[tempGlobalIndex].size = tokenval; + match(NUM); + } /* end if (lookahead == num) */ + else + { + error("Improperly formed array definition"); + return; + } /* end else */ + match(']'); + if (ErrorFlag) + return; + emit(GLO_DECL, tempGlobalIndex, 0.0); + DecCount += GlobalTable[tempGlobalIndex].size; + } /* end if next == '[' */ + else /* regular ID */ + { + GlobalIndex = GlobalInsert(lexbuf, ID, type, 1, 0, 0); + if (ErrorFlag) + return; + emit(GLO_DECL, GlobalIndex, 0.0); + ++DecCount; + match(ID); + if (ErrorFlag) + return; + } /* end else */ + } /* end else */ + } /* end GlobalScopeAndInsert */ + + /* ============================================================= */ + + void GlobalVarList(int type) + { + while (lookahead == ',') + { + match(','); + if (ErrorFlag) + return; + if (lookahead == ID || lookahead == ARRAY) + { + GlobalScopeAndInsert (type); + if (ErrorFlag) + return; + } /* end if ID or ARRAY */ + else + { + error("Expected an identifier or array"); + return; + } /* end else */ + } /* end while loop */ + } /* end GlobalVarList */ + + /* ============================================================= */ + + void exprTest(void) + { + int tempTrue, tempDone; + int tempOperation; + int TempFloatFlag; + + FloatFlag = 0; + FloatFlag = expr(); + if (ErrorFlag) + return; + + while ((lookahead == EQUAL) || (lookahead == NEQUAL)) + { + tempOperation = lookahead; + if (lookahead == EQUAL) + match(EQUAL); + else + match(NEQUAL); + if (ErrorFlag) + return; + TempFloatFlag = FloatFlag; + if (TempFloatFlag) + { + FloatFlag = 0; + FloatFlag = expr(); + if (!(FloatFlag)) + { emit(FLOAT, 0, 0.0); + FloatFlag = 1; + } + } + else + { + FloatFlag = expr(); + if (FloatFlag) + { + emit(NUM, 1, 0.0); + emit(IST, 0, 0.0); + emit(FLOAT, 0, 0.0); + emit(NUM, 1, 0.0); + emit(VAL, 0, 0.0); + } + } + if (ErrorFlag) + return; + emit(COMP, 0, 0.0); + tempTrue = LabelCounter; + ++LabelCounter; + tempDone = LabelCounter; + ++LabelCounter; + emit(PUSH_CODE_LABEL, tempTrue, 0.0); + if (tempOperation == EQUAL) + emit(BEQ, 0, 0.0); + else + emit(BNE, 0, 0.0); + emit(NUM, 0, 0.0); + emit(PUSH_CODE_LABEL, tempDone, 0.0); + emit(B, 0, 0.0); + emit(LABEL_CODE, tempTrue, 0.0); + emit(NUM, 1, 0.0); + emit(LABEL_CODE, tempDone, 0.0); + } /* end if */ + } /* end exprTest */ + + /* ========================================================================= */ + + void exprAssg(void) + { + int tempLocalIndex, tempGlobalIndex; /* temp indices during recursion */ + + switch (lookahead) + { + case ARRAY: + tempLocalIndex = LocalIndex; + tempGlobalIndex = GlobalIndex; + PushArrayCellAddr(); + if (ErrorFlag) + return; + if (NextLookahead == '=') + { + ArrayParsed = 0; + match(ARRAY); + if (ErrorFlag) + return; + match('='); + if (ErrorFlag) + return; + FloatFlag = 0; + exprAssg(); + if (ErrorFlag) + return; + if (tempLocalIndex) + { + if ((LocalTable[tempLocalIndex].type == INT) && (FloatFlag)) + { + emit(INT, 0, 0.0); + FloatFlag = 0; + } + else if ((LocalTable[tempLocalIndex].type == FLOAT) && ( !FloatFlag)) + { + emit(FLOAT, 0, 0.0); + FloatFlag = 1; + } + emit(STHB ,0 ,0.0); + } + else if (tempGlobalIndex) + { + if ((GlobalTable[tempGlobalIndex].type == INT) && (FloatFlag)) + { + emit(INT, 0, 0.0); + FloatFlag = 0; + } + else if((GlobalTable[tempGlobalIndex].type == FLOAT) && (!FloatFlag)) + { + emit(FLOAT, 0, 0.0); + FloatFlag = 1; + } + emit(STH, 0, 0.0); + } + emit(SWAP, 0, 0.0); + emit(POP, 0, 0.0); + } /* end if NextLookahead == '=' */ + else + { + exprTest(); + if (ErrorFlag) + return; + } /* end else of if lookahead == '=' */ + break; + case ID: + tempLocalIndex = LocalIndex; + tempGlobalIndex = GlobalIndex; + + if (NextLookahead == '=') + { + if (LocalIndex) + emit(PUSH_LOC_VAR_ADDR, LocalIndex, 0.0); + else if (GlobalIndex) + emit(PUSH_GLO_VAR_ADDR, GlobalIndex, 0.0); + else + { + error("Compiler error, variable lexeme not found in any table"); + return; + } + match(ID); + if (ErrorFlag) + return; + match('='); + if (ErrorFlag) + return; + FloatFlag = 0; + exprAssg(); + if (ErrorFlag) + return; + if (tempLocalIndex) + { + if ((LocalTable[tempLocalIndex].type == INT) && (FloatFlag)) + { + emit(INT, 0, 0.0); + FloatFlag = 0; + } + else if ((LocalTable[tempLocalIndex].type == FLOAT) && ( !FloatFlag)) + { + emit(FLOAT, 0, 0.0); + FloatFlag = 1; + } + emit(STHB, 0, 0.0); + } + else if (tempGlobalIndex) + { + if ((GlobalTable[tempGlobalIndex].type == INT) && (FloatFlag)) + { + emit(INT, 0, 0.0); + FloatFlag = 0; + } + else if((GlobalTable[tempGlobalIndex].type == FLOAT) && (!FloatFlag)) + { + emit(FLOAT, 0, 0.0); + FloatFlag = 1; + } + emit(STH, 0, 0.0); + } + emit(SWAP, 0, 0.0); + emit(POP, 0, 0.0); + } + else + { + exprTest(); + if (ErrorFlag) + return; + } + break; + default: + exprTest(); + if (ErrorFlag) + return; + } /* end switch */ + return; + } /* end exprAssg */ + + /* ========================================================================= */ + + void parseAStmt(void) /* parse a single statement */ + { + int tempLabel1, tempLabel2; + + switch (lookahead) + { + case WHILE: + match(WHILE); + if (ErrorFlag) + return; + tempLabel1 = LabelCounter; + ++LabelCounter; + tempLabel2 = LabelCounter; + ++LabelCounter; + emit(LABEL_CODE, tempLabel1, 0.0); + emit(PUSH_CODE_LABEL, tempLabel2, 0.0); + match('('); + if (ErrorFlag) + return; + FloatFlag = 0; + exprAssg(); + if (ErrorFlag) + return; + match(')'); + if (ErrorFlag) + return; + if (FloatFlag) + emit(RNUM, 0, 0.0); /* push 0.0 */ + else + emit(NUM, 0 ,0.0); /* push 0 */ + emit(COMP, 0, 0.0); + emit(BEQ, 0, 0.0); + parseAStmt(); + if (ErrorFlag) + return; + emit(PUSH_CODE_LABEL, tempLabel1, 0.0); + emit(B, 0, 0.0); + emit(LABEL_CODE, tempLabel2, 0.0); + break; + case IF: + match(IF); + if (ErrorFlag) + return; + tempLabel1 = LabelCounter; + ++LabelCounter; + emit(PUSH_CODE_LABEL, tempLabel1, 0.0); + match('('); + if (ErrorFlag) + return; + FloatFlag = 0; + exprAssg(); + if (ErrorFlag) + return; + match(')'); + if (ErrorFlag) + return; + if (FloatFlag) + emit(RNUM, 0, 0.0); /* push 0.0 */ + else + emit(NUM, 0, 0.0); /* push 0 */ + emit(COMP, 0, 0.0); + emit(BEQ, 0, 0.0); + parseAStmt(); + if (ErrorFlag) + return; + if (lookahead == ELSE) + { + match (ELSE); + if (ErrorFlag) + return; + tempLabel2 = LabelCounter; + ++LabelCounter; + emit(PUSH_CODE_LABEL, tempLabel2, 0.0); + emit(B, 0, 0.0); + emit(LABEL_CODE, tempLabel1, 0.0); + parseAStmt(); + if (ErrorFlag) + return; + emit(LABEL_CODE, tempLabel2, 0.0); + } /* end if lookahead == ELSE */ + else + { + emit(LABEL_CODE, tempLabel1, 0.0); + } /* end else lookahead == ELSE */ + break; + case '{': + match('{'); + do + { + parseAStmt(); + if (ErrorFlag) + ErrorFlag = 0; + } while ((lookahead != '}') && (lookahead != DONE)); + match('}'); + if (ErrorFlag) + return; + break; + case RETURN: + if (NextLookahead == ';') + { + match(RETURN); + if (ErrorFlag) + return; + match(';'); + if (ErrorFlag) + return; + if (GlobalTable[FuncNameIndex].type == INT) + emit(NUM, 1, 0.0); + else + emit(RNUM, 0, 1.0); + } /* end if */ + else + { + match(RETURN); + if (ErrorFlag) + return; + exprAssg(); + if (ErrorFlag) + return; + match(';'); + if (ErrorFlag) + return; + } /* end else */ + emit(PUSH_CODE_LABEL, ReturnLabel, 0.0); + emit(B, 0, 0.0); + break; + default: /* assignment statement */ + exprAssg(); + if (ErrorFlag) + return; + emit(POP, 0, 0.0); + match(';'); + return; + } /* end switch */ + return; + } /* end parseAStmt */ + + /* ========================================================================= */ + + void parse(void) /* parse a list of functions */ + { + /* prime NextLookahead */ + lookahead = 1; + match (lookahead); + if (ErrorFlag) + ErrorFlag = 0; + + /* prime lookahead */ + lookahead = 1; + match (lookahead); + if (ErrorFlag) + ErrorFlag = 0; + + DeclOrF(); /* parses the global var. declarations and the first function */ + if (ErrorFlag) + return; + FunctionList(); + if (ErrorFlag) + return; + CheckMain(); + AllBodsParsed(); + if (ErrorFlag) + return; + emit(END, 0, 0.0); + return; + } /* end parse */ + /* ========================================================================= */ + + + int factor(void) + { + int temp; + int tempLocalIndex, tempGlobalIndex; + char templexbuf[30]; + + switch(lookahead) { + case '(': + match('('); + if (ErrorFlag) + return -99; + switch (lookahead) + { + case INT: + match (INT); + if (ErrorFlag) + return -99; + match (')'); + if (ErrorFlag) + return -99; + + temp = factor(); + if (ErrorFlag) + return -99; + if (temp) + emit(INT, 0, 0.0); + return(0); + break; + + case FLOAT: + match (FLOAT); + if (ErrorFlag) + return -99; + match (')'); + if (ErrorFlag) + return -99; + + temp = factor(); + if (ErrorFlag) + return -99; + if ( !temp) + emit(FLOAT, 0, 0.0); + return(1); + break; + + default: + FloatFlag = 0; + exprAssg(); + if (ErrorFlag) + return -99; + match(')'); + if (ErrorFlag) + return -99; + if (FloatFlag) + return(1); + else + return(0); + break; + } /* end switch */ + break; + + case NUM: + emit(NUM, tokenval, 0.0); + match(NUM); + if (ErrorFlag) + return -99; + return(0); /* meaning false float flag */ + break; + + case RNUM: + emit(RNUM, tokenval, ftokenval); + match(RNUM); + if (ErrorFlag) + return -99; + return(1); /* meaning true float flag */ + break; + + case ID: + if (NextLookahead == '(') + { + /* function call */ + tempLocalIndex = LocalIndex; + tempGlobalIndex = GlobalIndex; + strcpy (templexbuf, lexbuf); + match(ID); + if (ErrorFlag) + return -99; + match('('); + if (ErrorFlag) + return -99; + ExprList(); + if (ErrorFlag) + return -99; + match(')'); + if (ErrorFlag) + return -99; + + /* prepare to branch to function */ + CallReturnAddr = LabelCounter; + ++LabelCounter; + emit(PUSH_CODE_LABEL, CallReturnAddr, 0.0); + emit(PUSH_FRAMESIZE, FuncNameIndex, 0.0); + emit(IB, 0, 0.0); + + /* branch to function */ + if (tempLocalIndex) + { + error("Function called is to a local variable"); + return -99; + } /* end LocalIndex */ + else if (tempGlobalIndex) + { + if (!(GlobalTable[tempGlobalIndex].function)) + { + error("Function called is to a global variable"); + return -99; + } /* end if !function */ + else + { + emit(PUSH_CODE_LABEL,GlobalTable[tempGlobalIndex].functionlabel,0.0); + } /* end else !function */ + } /* end GlobalIndex */ + else /* lexeme not in any symbol table */ + { + tempGlobalIndex = GlobalInsert (templexbuf,ID,INT,0,1,LabelCounter); + if (ErrorFlag) + ErrorFlag = 0; + ++LabelCounter; + emit(PUSH_CODE_LABEL, GlobalTable[tempGlobalIndex].functionlabel, 0.0); + } /* end insert function name */ + emit(B, 0, 0.0); + + /* return sequence */ + emit(LABEL_CODE, CallReturnAddr, 0.0); + emit(PUSH_FRAMESIZE, FuncNameIndex, 0.0); + emit(DB, 0, 0.0); + if (GlobalTable[tempGlobalIndex].function < 0) /* function defined */ + { + if (GlobalTable[tempGlobalIndex].type == INT) + return(0); + else + return(1); + } + else /* default return type of undefined function is INT */ + return(0); + } /* end if NextLookahead == ')' */ + else if ( !(LocalIndex || GlobalIndex)) + { + error("attempting to use an undefined variable"); + return -99; + } + + if (LocalIndex) + emit(PUSH_LOC_VAR_VALUE, LocalIndex, 0.0); + else if (GlobalIndex) + emit(PUSH_GLO_VAR_VALUE, GlobalIndex, 0.0); + else + { + error("Compiler error, lexeme was not found in any table"); + break; + } + tempLocalIndex = LocalIndex; + tempGlobalIndex = GlobalIndex; + match(ID); + if (ErrorFlag) + return -99; + if (tempLocalIndex) + { + if (LocalTable[tempLocalIndex].type == FLOAT) + return(1); + else + return(0); + } + else + { + if (GlobalTable[tempGlobalIndex].type == FLOAT) + return(1); + else + return(0); + } + break; + case ARRAY: + tempLocalIndex = LocalIndex; + tempGlobalIndex = GlobalIndex; + PushArrayCellAddr(); + if (ErrorFlag) + return -99; + ArrayParsed = 0; + match(ARRAY); + if (ErrorFlag) + return -99; + if (tempLocalIndex) + emit(VALB, 0, 0.0); + else if (tempGlobalIndex) + emit(VAL, 0, 0.0); + else + { + error("using an undefined array referance"); + return -99; + } + + if (tempLocalIndex) + { + if (LocalTable[tempLocalIndex].type == FLOAT) + return(1); + else + return(0); + } + else + { + if (GlobalTable[tempGlobalIndex].type == FLOAT) + return(1); + else + return(0); + } + break; + case '-': + match('-'); + if (ErrorFlag) + return -99; + temp=factor(); + if (ErrorFlag) + return -99; + if (temp) + emit(RNEG, 0, 0.0); + else + emit(NEG, 0, 0.0); + return(temp); + break; + case READF: + match(READF); + if (ErrorFlag) + return -99; + match ('('); + if (ErrorFlag) + return -99; + match (')'); + if (ErrorFlag) + return -99; + emit(READ, 0, 0.0); + emit(FLOAT, 0, 0.0); + return(1); + break; + case READI: + match(READI); + if (ErrorFlag) + return -99; + match('('); + if (ErrorFlag) + return -99; + match(')'); + if (ErrorFlag) + return -99; + emit(READ, 0, 0.0); + emit(INT, 0, 0.0); + return(0); + break; + case WRITEF: + match (WRITEF); + if (ErrorFlag) + return -99; + match('('); + if (ErrorFlag) + return -99; + FloatFlag = 0; + exprAssg(); + if (ErrorFlag) + return -99; + if ( !(FloatFlag)) + { + emit(FLOAT, 0, 0.0); + FloatFlag = 1; + } + match(')'); + if (ErrorFlag) + return -99; + emit(WRITEF, 0, 0.0); + emit(RNUM, 1, 1.0); + return(1); + break; + case WRITEI: + match(WRITEI); + if (ErrorFlag) + return -99; + match('('); + if (ErrorFlag) + return -99; + FloatFlag = 0; + exprAssg(); + if (ErrorFlag) + return -99; + if (FloatFlag) + { + emit(INT, 0, 0.0); + FloatFlag = 0; + } + match(')'); + if (ErrorFlag) + return -99; + emit(WRITEI, 0, 0.0); + emit(NUM, 1, 0.0); + return(0); + break; + case WRITELN: + match(WRITELN); + if (ErrorFlag) + return -99; + match('('); + if (ErrorFlag) + return -99; + match(')'); + if (ErrorFlag) + return -99; + emit(WRITELN, 0, 0.0); + emit(NUM, 1, 0.0); + return(0); + break; + default: + /* error used to be called from here */ + error("Illegal operator"); + return(0); + } + return -99; + } + + /* ------------------------------------------------------------------ */ + + void ExprList(void) + { + if (lookahead != ')') + { + exprAssg(); + if (ErrorFlag) + return; + + while (lookahead == ',') + { + match(','); + if (ErrorFlag) + return; + exprAssg(); + if (ErrorFlag) + return; + } /* end while */ + } /* end if ) */ + } /* end ExprList */ + + /* ========================================================================= */ + + + void FunctionList(void) + { + do + { + ErrorFlag = 0; + FloatFlag = 0; + LocalReset(); + switch(lookahead) + { + case ID: + FunctionDef(INT); + if (ErrorFlag) + return; + break; + case INT: + match(INT); + if (ErrorFlag) + return; + FunctionDef(INT); + if (ErrorFlag) + return; + break; + case FLOAT: + match(FLOAT); + if (ErrorFlag) + return; + FunctionDef(FLOAT); + if (ErrorFlag) + return; + case DONE: + break; + default: + error("Unexpected token found"); + return; + break; + } /* end for switch statement */ + } + while (lookahead != DONE); + } /* end FunctionList */ + + /* ----------------------------------------------------------------------- */ + + void FunctionDef(int type) + { + offset = 1; + if (lookahead != ID) + { + error("Invalid function defintion structure. Expected ID"); + return; + } /* end if lookahead */ + + if (LocalIndex) + { + error("Compiler error, function name in local symbol table"); + return; + } /* end if LocalIndex */ + else if (GlobalIndex) + { + if (!(GlobalTable[GlobalIndex].function)) + { + error("Attempting to redefine a global variable as a function name"); + return; + } /* end if GlobalTable */ + else if (GlobalTable[GlobalIndex].function < 0) + { + error("Redefining a function."); + return; + } /* end else if GlobalTable */ + else if (GlobalTable[GlobalIndex].function > 0) + /* function is a postive value, already called not defined */ + { + GlobalTable[GlobalIndex].type = type; + FuncNameIndex = GlobalIndex; + GlobalTable[GlobalIndex].function = -1; + } /* end else if function > 0 */ + else + { + error("Compiler error, functiondef is confused"); + return; + } + } /* end else if (GlobalIndex) */ + else /* ID not in any tabel */ + { + GlobalIndex = GlobalInsert (lexbuf,ID,type,0,-1,LabelCounter); + if (ErrorFlag) + ErrorFlag = 0; + FuncNameIndex = GlobalIndex; + ++LabelCounter; + } /* end else */ + + Scope = GlobalTable[GlobalIndex].functionlabel; + + /* label function */ + emit(LABEL_FUNC, GlobalIndex, 0.0); + emit(LABEL_CODE, Scope, 0.0); + + /* store return address */ + emit(STORE_RA, FuncNameIndex, 0.0); + + ReturnLabel = LabelCounter; + ++LabelCounter; + + match(ID); + if (ErrorFlag) + ErrorFlag = 0; + match('('); + if (ErrorFlag) + ErrorFlag = 0; + if ( strcmp(GlobalTable[FuncNameIndex].lexptr, "main") == 0) + { + if (lookahead == ')') + { + match(')'); + if (ErrorFlag) + return; + } /* end if lookahead == ')' */ + else + { + error("Function main cannot have parameters."); + return; + } /* end else */ + } /* end if function is main */ + else + { + ParamList(); + if (ErrorFlag) + ErrorFlag = 0; + match(')'); + if (ErrorFlag) + ErrorFlag = 0; + } /* end else (function is something other than main) */ + DecList(); + if (ErrorFlag) + ErrorFlag = 0; + emit(SAVE_FRAMESIZE, FuncNameIndex, 0.0); + FstmtList(); + if (ErrorFlag) + return; + if (GlobalTable[FuncNameIndex].type == INT) + emit(NUM, 1, 0.0); + else + emit(RNUM, 0, 1.0); + emit(LABEL_CODE, ReturnLabel, 0.0); + emit(PUSH_RA, FuncNameIndex, 0.0); + emit(B, 0, 0.0); + } /* end function Def */ + + /* ---------------------------------------------------------------------- */ + + void MoreParams(void) + { + int tempLocalIndex; + + if (lookahead == ',') + { + match(','); + if (ErrorFlag) + return; + if (lookahead != ID) + { + error("Improperly formed parameter list"); + return; + } + if (GlobalIndex) + { + + if (GlobalTable[GlobalIndex].function) + { + error("Cannot use a function name as parameter"); + return; + } /* end if GlobalTable */ + } /* GlobalIndex */ + + if (LocalIndex) + { + error("Trying to use a prameter twice"); + return; + } /* end else if (LocalIndex) */ + + else + { + tempLocalIndex = LocalIndex = LocalInsert (lexbuf,ID,PARAM,1,0,0); + if (ErrorFlag) + return; + } /* end else */ + match (ID); + if (ErrorFlag) + return; + MoreParams(); + if (ErrorFlag) + return; + emit(LOC_DECL, tempLocalIndex, 0.0); + emit(PUSH_LOC_VAR_ADDR, tempLocalIndex, 0.0); + emit(ISTB, 0, 0.0); + ++offset; + } /* end if lookahead == ',' */ + } /* end MoreParams() */ + + + /* ---------------------------------------------------------------------- */ + + void ParamList(void) + { + int tempLocalIndex; + + if (lookahead == ID) + { + if (GlobalIndex) + { + + if (GlobalTable[GlobalIndex].function) + { + error("Cannot use a function name as parameter"); + return; + } /* end if GlobalTable */ + } /* GlobalIndex */ + + if (LocalIndex) + { + error("Trying to use a parameter twice"); + return; + } /* end else if (LocalIndex) */ + + else + { + tempLocalIndex = LocalIndex = LocalInsert (lexbuf,ID,PARAM,1,0,0); + if (ErrorFlag) + return; + } /* end else */ + match (ID); + if (ErrorFlag) + return; + MoreParams(); + if (ErrorFlag) + return; + emit(LOC_DECL, tempLocalIndex, 0.0); + emit(PUSH_LOC_VAR_ADDR, tempLocalIndex, 0.0); + emit(ISTB, 0, 0.0); + ++offset; + } /* end if lookahead == ID */ + } /* end paramlist() */ + + /* ------------------------------------------------------------------ */ + + void DecList(void) + { + while ((lookahead == INT) || (lookahead == FLOAT)) + { + match (lookahead); /* obviously must be INT or FLOAT */ + if (ErrorFlag) + return; + VarList (PreviousLookahead); + if (ErrorFlag) + return; + } /* end while ((lookahead == INT) || (loookahead == FLOAT)) */ + ParamInt(); + } /* end function DecList */ + + /* --------------------------------------------------------------------- */ + + void VarList(int type) + { + int tempLocalIndex; + + do + { + if (GlobalIndex) + { + + if (GlobalTable[GlobalIndex].function) + { + error ("Cannot use a function name as a parameter"); + return; + } /* end if GlogalTable */ + } /* end if (GlobalIndex) */ + + if (LocalIndex) + { + + if (LocalTable[LocalIndex].type == PARAM) + { + if (NextLookahead == '[') + error ("Cannot pass an array as a parameter"); + else + { + LocalTable[LocalIndex].type = type; + match(ID); + if (ErrorFlag) + return; + } /* end else */ + } /* end if LocalTable[LocalIndex] */ + + else + { + error ("Trying to redefine a variable"); + return; + } /* end else */ + } /* end if LocalIndex */ + + else /* variable is not entered as a local so insert */ + { + if (NextLookahead == '[') + { + tempLocalIndex = LocalIndex = LocalInsert (lexbuf,ARRAY,type,0,0,0); + if (ErrorFlag) + return; + lookahead = ARRAY; + match (ARRAY); + if (ErrorFlag) + return; + match ('['); + if (ErrorFlag) + return; + if (lookahead == NUM) + { + LocalTable[tempLocalIndex].size = tokenval; + if (ErrorFlag) + return; + } + else + { + error("Array declarations requires an integer within []"); + return; + } + match (NUM); + if (ErrorFlag) + return; + match (']'); + if (ErrorFlag) + return; + emit(LOC_DECL, tempLocalIndex, 0.0); + offset += LocalTable[tempLocalIndex].size; + } /* end if nextlook */ + + else + { + LocalIndex = LocalInsert(lexbuf,ID,type,1,0,0); + if (ErrorFlag) + return; + emit(LOC_DECL, LocalIndex, 0.0); + ++offset; + match (ID); + if (ErrorFlag) + return; + } /* end else */ + } /* end else */ + + switch (lookahead) + { + case ',': + match (','); + if (ErrorFlag) + return; + break; + case ';': + match (';'); + if (ErrorFlag) + return; + return; + break; + default: + error ("badly formed declarations"); + return; + } /* end switch (lookahead) */ + } while ((lookahead == ID) || (lookahead == ARRAY)); + error("can only use ID or ARRAAY"); + return; + } /* end function VarList */ + + /* ------------------------------------------------------------------- */ + + void FstmtList(void) + { + match ('{'); + if (ErrorFlag) + ErrorFlag = 0; + + do + { + parseAStmt(); + if (ErrorFlag) + ErrorFlag = 0; + } + while ((lookahead != '}') && (lookahead != DONE)); + + if (lookahead == DONE) + { + error("Unexpected end of file"); + return; + } /* end if */ + else + { + match ('}'); + if (ErrorFlag) + return; + } /* end else */ + } /* end function FstmtList */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/symbol.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/symbol.c:1.1 *** /dev/null Tue Oct 5 14:24:17 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/compiler/symbol.c Tue Oct 5 14:24:06 2004 *************** *** 0 **** --- 1,196 ---- + /**** symbol.c *****************************************************/ + + #include "global.h" + + extern void error(char *m); + extern void emit(int t, int tval, float rval); + + char Glexemes[STRMAX]; /* char array to hold global lexemes */ + char Llexemes[STRMAX]; /* char array to hold local lexemes */ + /* struct entry LocalTable[SYMMAX]; define the size of the local table */ + /* struct entry GlobalTable[SYMMAX]; define the size of the global table */ + int Glastchar = - 1; /* last used position in Glexemes */ + int Llastchar = - 1; /* last used position in Llexemes */ + int Glastentry = 0; /* last used position in global table */ + int Llastentry = 0; /* last usedentry in local table */ + + /* ---------------------------------------------------------------- */ + + void OutputLocal(void) /* function used for testing only */ + { + int i; /* temporary index */ + + printf("\n\nLOCAL SYMBOL TABLE\n------------------\n"); + for (i = 0; i <= Llastentry; i++) + { + printf("%s\t%d\t%d\t%d\t%d\t%d\n", LocalTable[i].lexptr, + LocalTable[i].token, + LocalTable[i].type, + LocalTable[i].size, + LocalTable[i].function, + LocalTable[i].functionlabel); + } /* end for */ + printf("\n\n"); + } /* end OutputLocal */ + + /* ----------------------------------------------------------------- */ + + void OutputGlobal(void) /* function used for testing only */ + { + int i; /* temporary index */ + + printf("\n\nGLOBAL SYMBOL TABLE\n-------------------\n"); + for (i = 0; i <= Glastentry; i++) + { + printf("%s\t%d\t%d\t%d\t%d\t%d\n", + GlobalTable[i].lexptr, + GlobalTable[i].token, + GlobalTable[i].type, + GlobalTable[i].size, + GlobalTable[i].function, + GlobalTable[i].functionlabel); + } /* end for */ + printf("\n\n"); + } /* end OutputGlobal */ + + /* ----------------------------------------------------------------- */ + + + int GlobalLookup(char s[]) /* returns position of entry for s */ + { + int p; + for (p = Glastentry; p > 0; p = p - 1) + if (strcmp(GlobalTable[p].lexptr, s) == 0) + return p; + return 0; + } + + /* ----------------------------------------------------------------- */ + + int LocalLookup(char s[]) /* returns position of entry for s */ + { + int p; + for (p = Llastentry; p > 0; p = p - 1) + if (strcmp(LocalTable[p].lexptr, s) == 0) + return p; + return 0; + } + + /* ----------------------------------------------------------------- */ + + int GlobalInsert(char s[], int tok, int type, int size, int function, int functionlabel) + + /* returns position of entry for s */ + { + int len; + + len = strlen(s); /* strlen computes length of s */ + if (Glastentry + 1 >= SYMMAX) + { + error("symbol table full"); + return (0); + } + if (Glastchar + len + 1 >= STRMAX) + { + error("lexemes array full"); + return (0); + } + Glastentry = Glastentry + 1; + GlobalTable[Glastentry].token = tok; + GlobalTable[Glastentry].lexptr = &Glexemes[Glastchar + 1]; + Glastchar = Glastchar + len + 1; + (void) strcpy(GlobalTable[Glastentry].lexptr, s); + GlobalTable[Glastentry].type = type; + GlobalTable[Glastentry].size = size; + GlobalTable[Glastentry].function = function; + GlobalTable[Glastentry].functionlabel = functionlabel; + return Glastentry; + } + + /* ----------------------------------------------------------------- */ + + int LocalInsert(char s[], int tok, int type, int size,int function,int functionlabel) + + /* returns position of entry for s */ + + { + int len; + + len = strlen(s); /* strlen computes length of s */ + if (Llastentry + 1 >= SYMMAX) + { + error("symbol table full"); + return (0); + } + if (Llastchar + len + 1 >= STRMAX) + { + error("lexemes array full"); + return (0); + } + Llastentry = Llastentry + 1; + LocalTable[Llastentry].token = tok; + LocalTable[Llastentry].lexptr = &Llexemes[Llastchar + 1]; + Llastchar = Llastchar + len + 1; + (void) strcpy(LocalTable[Llastentry].lexptr, s); + LocalTable[Llastentry].type = type; + LocalTable[Llastentry].size = size; + LocalTable[Llastentry].function = function; + LocalTable[Llastentry].functionlabel = functionlabel; + return Llastentry; + } + + /* ------------------------------------------------------------------ */ + + void ParamInt(void) + /* This function changes all PARAM fields to INT in local table */ + + { + int p; + + for (p = Llastentry; p > 0; p = p - 1) + if (LocalTable[p].type == PARAM) + LocalTable[p].type = INT; + } /* end ParamInt */ + + + /* ------------------------------------------------------------------ */ + + void LocalReset(void) /* this function effectively erases the local symbol table */ + { + Llastchar = - 1; + Llastentry = 0; + } /* end LocalReset */ + + /* ------------------------------------------------------------------ */ + + void AllBodsParsed(void) + { + int p; + int tmpflag = 0; + + for (p = Glastentry; p > 0; --p) + { + if (GlobalTable[p].function > 0) + { + emit(NOTDEC, p, 0.0); + tmpflag = 1; + } /* end if statement */ + } /* end for loop */ + ErrorFlag = tmpflag; + } /* end function */ + + /* ----------------------------------------------------------- */ + + void CheckMain(void) + { + int temp; + + temp = GlobalLookup("main"); + + if (GlobalTable[temp].function > 0) + { + error("Main never declared"); + GlobalTable[temp].function = -1; + } + ErrorFlag = 0; /* will get set again in parse's call to AllBodsParsed */ + } /* end check main */ From lattner at cs.uiuc.edu Tue Oct 5 14:29:52 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 14:29:52 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/ Message-ID: <200410051929.OAA24350@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 14:30:02 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 14:30:02 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/Makefile add.c bind.c compare.c dixie.h error.c globals.c init.c list.c modify.c modrdn.c parse.c read.c remove.c search.c send.c test.c util.c version.c Message-ID: <200410051930.OAA24406@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie: Makefile added (r1.1) add.c added (r1.1) bind.c added (r1.1) compare.c added (r1.1) dixie.h added (r1.1) error.c added (r1.1) globals.c added (r1.1) init.c added (r1.1) list.c added (r1.1) modify.c added (r1.1) modrdn.c added (r1.1) parse.c added (r1.1) read.c added (r1.1) remove.c added (r1.1) search.c added (r1.1) send.c added (r1.1) test.c added (r1.1) util.c added (r1.1) version.c added (r1.1) --- Log message: Another "benchmark" without an input --- Diffs of the changes: (+2259 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/Makefile:1.1 *** /dev/null Tue Oct 5 14:30:01 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/Makefile Tue Oct 5 14:29:50 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = dixie + #STDIN_FILENAME = $(SourceDir)/testset + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/add.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/add.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/add.c Tue Oct 5 14:29:50 2004 *************** *** 0 **** --- 1,54 ---- + /* + * Copyright (c) 1990 Regents of the University of Michigan. + * All rights reserved. + * + * add.c + */ + + #ifndef lint + static char copyright[] = "@(#) Copyright (c) 1990 Regents of the University of Michigan.\nAll rights reserved.\n"; + #endif + + #include + #include "dixie.h" + #include + + extern int dxi_send( char type, char *buf, int buflen, char *answer, int + anslen, int scope ); + + /* + * dxi_add - do a dixie (X.500) add operation. The DN of the entry to + * add is supplied (in text form) in who. The attributes that the new + * entry will have are supplied in the array of char *'s entry. + * + * Example: + * dxi_add( "c=us at cn=bob", entry ) + */ + + int dxi_add(char *who, char **entry ) + { + int i, len; + char *tmp; + char ans[ DXI_H_SIZE + 1 ]; + extern char *dxi_buffer; + extern int dxi_errno; + + strcpy( dxi_buffer, who ); + len = strlen( dxi_buffer ) + 1; + tmp = dxi_buffer + len; + for ( i = 0; entry[i] != NULL; i++ ) { + strcpy( tmp, entry[i] ); + len += strlen( entry[i] ) + 1; + tmp = dxi_buffer + len; + } + + /* and now ship it */ + if ( (i = dxi_send( DXI_ADD, dxi_buffer, len, ans, sizeof(ans), 0 )) + == -1 ) { + dxi_errno = DXI_DOWN; + return( -1 ); + } + dxi_errno = ans[DXI_H_RC]; + + return( dxi_errno == DXI_SUCCESS ? 0 : -1 ); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/bind.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/bind.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/bind.c Tue Oct 5 14:29:50 2004 *************** *** 0 **** --- 1,145 ---- + /* + * Copyright (c) 1990 Regents of the University of Michigan. + * All rights reserved. + * + * bind.c + */ + + #ifndef lint + static char copyright[] = "@(#) Copyright (c) 1990 Regents of the University of Michigan.\nAll rights reserved.\n"; + #endif + + #include + #include + #include "dixie.h" + #include + #if defined(MACOS) || defined(DOS) || defined(VMS) + #include + #include + #ifdef MACOS + #include "tcp.h" + #endif + #ifdef VMS + #include + #endif + #else + #include + #include + #endif + + extern int dxi_limit; + extern char *dxi_buffer; + extern int dxi_errno; + extern int dxi_debug; + extern int dxi_bound; + + extern int dxi_send( char type, char *buf, int buflen, char *answer, int anslen, int scope ); + extern int open_sock( unsigned long address, int port ); + extern u_long inet_addr( char *s ); + + int nullbound; + + /* + * dxi_udpbind - bind to the dixie server (and X.500). The dn and password + * of the entry to which to bind are supplied. 0 is returned on success, + * -1 if the DSA could not be contacted, or the length of the error packet + * in case or other trouble. + * + * Example: + * dxi_udpbind( "c=us at o=university of michigan at cn=manager", "secret" ) + */ + + int dxi_udpbind(char *who, char *passwd) + { + char answer[256]; + char *temp; + int len, i; + unsigned long address; + int port; + + dxi_errno = 0; + + /* + * build the packet. it looks like this: + * who\0passwd\0 + */ + + nullbound = (who == NULL || *who == '\0'); + if ( who == NULL ) + who = ""; + if ( passwd == NULL ) + passwd = ""; + strcpy( dxi_buffer, who ); + len = strlen( who ) + 1; + temp = dxi_buffer + len; + strcpy( temp, passwd ); + len += strlen( passwd ); + dxi_buffer[len++] = '\0'; + + /* send it */ + if ( (len = dxi_send( DXI_BIND, dxi_buffer, len, answer, + sizeof(answer), 0 )) < 0 ) { + dxi_errno = DXI_DOWN; + return( len ); + } + dxi_errno = answer[DXI_H_RC]; + + /* see if it was successful */ + switch ( dxi_errno ) { + case DXI_SUCCESS : + if ( dxi_bound >= 0 ) + return( 0 ); + temp = NULL; + for ( i = DXI_H_SIZE; i < len; i++ ) { + if ( answer[i] == DXI_VAL_SEP ) { + answer[i] = '\0'; + if ( temp == NULL ) + temp = &(answer[i + 1]); + } + } + address = inet_addr( &(answer[DXI_H_SIZE]) ); + port = atoi( temp ); + dxi_bound = open_sock( address, port ); + return( dxi_bound < 0 ? -1 : 0 ); + + default: + return( -1 ); + } + } + + /* + * dxi_bind - bind to the dixie server (and X.500). The dn and password + * of the entry to which to bind are supplied. 0 is returned on success, + * -1 if the DSA could not be contacted, or the length of the error packet + * in case or other trouble. This bind is done via TCP. + * + * Example: + * dxi_bind( "c=us at o=university of michigan at cn=manager", "secret" ) + */ + + #if defined(MACOS) || defined(DOS) + extern ip_addr dixieaddr; + #else + extern struct sockaddr_in dixieaddr; + #endif + + int dxi_bind( char *who, char *passwd ) + { + nullbound = (who == NULL || *who == '\0'); + if ( dxi_bound >= 0 ) + return( dxi_udpbind( who, passwd ) ); + #if defined(MACOS) || defined(DOS) + dxi_bound = open_sock( dixieaddr, DXI_PORT ); + #else + dxi_bound = open_sock( dixieaddr.sin_addr.s_addr, DXI_PORT ); + #endif + + if ( dxi_bound < 0 ) + return( -1 ); + + dxi_errno = DXI_SUCCESS; + if ( who == NULL || *who == '\0' ) + return( 0 ); + + return( dxi_udpbind( who, passwd ) ); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/compare.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/compare.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/compare.c Tue Oct 5 14:29:50 2004 *************** *** 0 **** --- 1,56 ---- + /* + * Copyright (c) 1990 Regents of the University of Michigan. + * All rights reserved. + * + * compare.c + */ + + #ifndef lint + static char copyright[] = "@(#) Copyright (c) 1990 Regents of the University of Michigan.\nAll rights reserved.\n"; + #endif + + #include + #include "dixie.h" + #include + + extern int dxi_send( char type, char *buf, int buflen, char *answer, int anslen, int scope ); + + /* + * dxi_compare - do a dixie (X.500) compare operation. The DN of the entry + * is supplied (in text form), along with the attribute and value to compare + * (in attr and value). + * + * Example: + * dxi_compare( "c=us at cn=bob", "userPassword", "foo") + */ + + int dxi_compare( char *who, char *attr, char *value) + { + int len; + extern char *dxi_buffer; + extern int dxi_errno; + char ans[ DXI_H_SIZE + 1 ]; + char *p; + + strcpy( dxi_buffer, who ); + len = strlen( who ); + p = &dxi_buffer[len]; + p++; + len++; + strcpy(p,attr); + p += strlen(attr) + 1; + len += strlen(attr) + 1; + strcpy(p,value); + len += strlen(value) + 1; + /* and now ship it */ + + if ( dxi_send( DXI_COMPARE, dxi_buffer, len, ans, sizeof(ans), 0 ) + == -1 ) { + dxi_errno = DXI_DOWN; + return( -1 ); + } + dxi_errno = ans[DXI_H_RC]; + + return( dxi_errno == DXI_SUCCESS ? 0 : + dxi_errno == DXI_COMPAREFAILED ? 1 : -1 ); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/dixie.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/dixie.h:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/dixie.h Tue Oct 5 14:29:50 2004 *************** *** 0 **** --- 1,173 ---- + /* dixie.h */ + /* + * Copyright (c) 1990 Regents of the University of Michigan. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that this notice is preserved and that due credit is given + * to the University of Michigan at Ann Arbor. The name of the University + * may not be used to endorse or promote products derived from this + * software without specific prior written permission. This software + * is provided ``as is'' without express or implied warranty. + */ + + #ifdef MACOS + #include "macos.h" + #define NOUDP 1 + #define NEEDINETADDR 1 + #endif + + #ifdef DOS + #define NOUDP 1 + + typedef unsigned short us; + typedef unsigned long ul; + #define ntohs(i) ((us)( (((us)i & 0xff) << 8) + (((us)i & 0xff00) >> 8) )) + #define ntohl(i) ((ul)( (((ul)i & 0xff) << 24) + (((ul)i & 0xff00) << 8) + \ + (((ul)i & 0xff0000) >> 8) + \ + (((ul)i & 0xff000000) >> 24) )) + #define htons(i) ((unsigned) (((unsigned)i & 0xff00) >> 8) + \ + (((unsigned) i & 0xff) << 8)) + + typedef unsigned long ip_addr; + typedef unsigned long u_long; + typedef unsigned char u_char; + + #include + #include "proto.h" + #endif /* DOS */ + + #define DXI_PORT 96 + + #define K 1024 + #define MAX_PKT_SIZE (30*K) + #define MAX_PKT_FRAG (K/2) + + /* dixie op codes */ + #define DXI_READ 0x01 + #define DXI_WRITE 0x02 + #define DXI_SEARCH 0x03 + #define DXI_BIND 0x04 + #define DXI_SEARCH1 0x05 + #define DXI_ACK 0x06 + #define DXI_NACK 0x07 + #define DXI_SEARCH_APPROX 0x08 + #define DXI_SEARCH_EXACT 0x09 + #define DXI_RESEND 0x0a + #define DXI_PING 0x0b + #define DXI_SEARCH_ISUB 0x0c + #define DXI_SEARCH_FSUB 0x0d + #define DXI_SEARCH_IFSUB 0x0e + #define DXI_SEARCH_GEN 0x0f + #define DXI_LIST 0x10 + #define DXI_ADD 0x11 + #define DXI_REMOVE 0x12 + #define DXI_MODRDN 0x13 + #define DXI_COMPARE 0x14 + + /* dixie search scopes */ + #define DXI_SRCH_BASE 0x01 + #define DXI_SRCH_ONELEVEL 0x02 + #define DXI_SRCH_SUBTREE 0x03 + + /* dixie return values */ + #define DXI_SUCCESS 0x01 + #define DXI_NOTFOUND 0x02 + #define DXI_ERROR 0x03 + #define DXI_BADCMD 0x04 + #define DXI_REFUSED 0x05 + #define DXI_BADDN 0x06 + #define DXI_SIZELIMIT 0x07 + #define DXI_NOTCONN 0x08 + #define DXI_SEQNOTFOUND 0x09 + #define DXI_BAD_ATTR 0x0a + #define DXI_NEX_ATTR 0x0b + #define DXI_BAD_ATTRVAL 0x0c + #define DXI_NEX_ATTRVAL 0x0d + #define DXI_NO_RDN_MOD 0x0e + #define DXI_NAME_ERROR 0x0f + #define DXI_REFER_ERROR 0x10 + #define DXI_DSA_DOWN 0x11 + #define DXI_TIMELIMIT 0x12 + #define DXI_TOOBIG 0x13 + #define DXI_DOWN 0x14 + #define DXI_EXISTS 0x15 + #define DXI_COMPAREFAILED 0x16 + #define DXI_BAD_FILTER 0x17 + + /* for compatibility ... */ + #define DXI_LIMIT 0x07 + + #define DXI_VAL_SEP 0x01 + #define DXI_ATR_SEP 0x02 + #define DXI_DNS_SEP 0x03 + #define DXI_ATEND_FLAG 0x04 + + #define DXI_H_RC 0 /* char */ + #define DXI_H_OP 0 /* char */ + #define DXI_H_ID 1 /* short */ + #define DXI_H_TOTLEN 3 /* long */ + #define DXI_H_SEQUENCE 7 /* short */ + #define DXI_H_OPTIONS 9 /* char */ + #define DXI_H_VERSION 10 /* char */ + #define DXI_H_SRCH_SCOPE 11 /* char */ + #define DXI_H_TIMELIMIT 12 /* short */ + #define DXI_H_SIZELIMIT 14 /* short */ + #define DXI_H_SIZE 16 /* unused */ + + #define DXI_OPT_FILEATTR 1 + #define DXI_OPT_DONTDEREF 2 + #define DXI_OPT_DONTSEARCHALIASES 4 + + #define DXI_PHOTO_G3FAX_TWODIM 0x01 + #define DXI_PHOTO_JPEG 0x02 + + #define ID short + + #if !defined(MACOS) & !defined(DOS) + extern int bprint(); + + extern int dxi_init(char *host, int timeout, int retries); + extern int dxi_bind(char *who, char *passwd); + extern int dxi_udpbind(char *who, char *passwd); + extern int dxi_read(char *who, char **attrs, char *ans); + extern int dxi_list(char *who, char *ans); + extern int dxi_search(char *base, int scope, char *filter, char *attrlist[], + char *answer); + extern int dxi_modify(char *who, char **what); + extern int dxi_modrdn(char *who, char *newrdn); + extern int dxi_add(char *who, char **entry); + extern int dxi_remove(char *who); + extern void dxi_perror(char *s); + extern int dxi_matches(char *buf); + extern int dxi_close(void); + extern int dxi_compare(char *who, char *attr, char *value); + extern void dxi_det61(char *s); + + extern char *dxi_firstentry(char *buf); + extern char *dxi_nextentry(void); + extern char *dxi_getdn(char *buf); + extern char *dxi_lastdncomp(char *dn); + extern char *dxi_firstattr(char *ent); + extern char *dxi_nextattr(char *attr); + + extern char **dxi_getvalues(char *buf, char *at); + + extern void dxi_valuefree(char **av); + #endif /* MACOS DOS */ + + extern int dxi_debug; + extern int dxi_errno; + extern int dxi_not61; + extern char dxi_options; + extern short dxi_sizelimit; + extern short dxi_timelimit; + extern char *dxi_errlist[]; + #ifdef VMS + #define index(x) strchr(x) + #define rindex(x) strrchr(x) + #endif + + #ifdef __svr4__ + #define bzero(x,y) memset(x,0,y) + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/error.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/error.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/error.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,43 ---- + #include + #include "dixie.h" + #include + + #ifdef VMS_MULTINET + extern char *dxierrlist[20]; + #else + char *dxi_errlist[] = { + "Invalid error", /* 0 is not valid */ + "Success", /* DXI_SUCCESS */ + "No matches found", /* DXI_NOTFOUND */ + "Generic DIXIE error", /* DXI_ERROR */ + "Unknown op code", /* DXI_BADCMD */ + "Access denied", /* DXI_REFUSED */ + "Malformed DN", /* DXI_BADDN */ + "Size limit exceeded", /* DXI_SIZELIMIT */ + "Not bound", /* DXI_NOTCONN */ + "Fragment not found", /* DXI_SEQNOTFOUND */ + "Invalid attribute type", /* DXI_BAD_ATTR */ + "Attribute type not found", /* DXI_NEX_ATTR */ + "Invalid attribute value", /* DXI_BAD_VALUE */ + "Attribute value not found", /* DXI_NEX_VALUE */ + "ModRDN not allowed", /* DXI_NO_RDN_MOD */ + "Entry does not exist", /* DXI_NAME_ERROR */ + "Referral error", /* DXI_REFER_ERROR */ + "Can't contact DSA", /* DXI_DSA_DOWN */ + "Time limit exceeded", /* DXI_TIMELIMIT */ + "UDP packet too big", /* DXI_TOOBIG */ + "Can't contact DIXIE server", /* DXI_DOWN */ + "Attr, value, or name already exists", /* DXI_EXISTS */ + "Compare failed", /* DXI_COMPAREFAILED */ + "Bad search filter" /* DXI_BAD_FILTER */ + }; + #endif /* vms_multinet */ + + void dxi_perror( char *s ) + { + if ( dxi_errno <= DXI_BAD_FILTER && dxi_errno >= DXI_SUCCESS ) { + fprintf( stderr, "%s: %s\n", s, dxi_errlist[dxi_errno] ); + } else { + fprintf( stderr, "%s: Unknown error\n", s ); + } + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/globals.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/globals.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/globals.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,14 ---- + #include "dixie.h" + + char *dxi_buffer; + int dxi_errno; + int dxi_limitiserror; + int dxi_limit; + int dxi_debug; + int dxi_bound = -1; + int dxi_timeout; + int dxi_retries; + int dxi_not61; + char dxi_options; + short dxi_sizelimit; + short dxi_timelimit; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/init.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/init.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/init.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,103 ---- + /* + * Copyright (c) 1990 Regents of the University of Michigan. + * All rights reserved. + * + * show.c + */ + + #ifndef lint + static char copyright[] = "@(#) Copyright (c) 1990 Regents of the University of Michigan.\nAll rights reserved.\n"; + #endif + + #include "dixie.h" + #include + #include + #include + #if !defined(__STDC__) && !defined(VMS) + #include + #endif + #ifdef DOS + #include + #endif + #if defined(MACOS) || defined(DOS) + #include + #include "tcp.h" + #else + #include + #include + #include + #include + #endif + + #ifndef INADDR_LOOPBACK + #define INADDR_LOOPBACK 0x7f000001 + #endif + + extern u_long inet_addr( char *s ); + extern int add_server( u_long ns ); + + /* + * dxi_init - initialize the dixie library. host is used as the dixie + * host, timeout and retries as the default initial number of seconds + * to wait before retransmitting packets, and number of retries to make, + * respectively. Supplying 0 for timeout or retries resorts to the + * default values of 2 and 4, respectively. Supplying NULL for the host + * causes the localhost to be used. + * + * Example: + * dxi_init( "some.host.some.domain", 2, 4 ) + */ + + int dxi_init( char *host, int timeout, int retries ) + { + #if defined(MACOS) || defined(DOS) + struct hostInfo *hip; + #else + extern void attempt_rebind(); + struct hostent *hp; + #endif + unsigned long server; + extern char *dxi_buffer; + extern int dxi_timeout, dxi_retries; + + dxi_errno = DXI_ERROR; /* pessimistic, but efficient... */ + if ( dxi_buffer == NULL ) { + if ( (dxi_buffer = (char *) malloc( MAX_PKT_SIZE )) == NULL ) + return( -1 ); + } + + if ( host != NULL ) { + #if defined(MACOS) || defined(DOS) + if ( (hip = gethostinfobyname( host )) == NULL ) { + return( -1 ); + } + (void) memcpy( (char *) & server, (char *) &hip->addr[ 0 ], + sizeof(long) ); + + #else + if ( (server = inet_addr( host )) == -1 ) { + if ( (hp = gethostbyname( host )) == NULL ) { + return( -1 ); + } + (void) memcpy( (char *) &server, (char *) hp->h_addr, + sizeof(long) ); + } + #endif + } else { + server = INADDR_LOOPBACK; + } + + if ( add_server( server ) < 0 ) + return( -1 ); + + #if !defined(MACOS) && !defined(DOS) + (void) signal( SIGPIPE, attempt_rebind ); + #endif + + dxi_timeout = timeout <= 0 ? 2 : timeout; + dxi_retries = retries <= 0 ? 4 : retries; + dxi_options = 0; + + dxi_errno = DXI_SUCCESS; + return( 0 ); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/list.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/list.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/list.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,50 ---- + /* + * Copyright (c) 1990 Regents of the University of Michigan. + * All rights reserved. + * + * list.c + */ + + #ifndef lint + static char copyright[] = "@(#) Copyright (c) 1990 Regents of the University of Michigan.\nAll rights reserved.\n"; + #endif + + #include "dixie.h" + #include + #include + + /* + * dxi_list - do a dixie (X.500) list operation. The DN of the entry to + * list is supplied (in text form). The result of the list + * is passed back in ans, which should point to enough space. + * + * Example: + * dxi_list( "c=us at cn=bob", answerbuffer ) + */ + + extern int dxi_send( char type, char *buf, int buflen, char *answer, int anslen, int scope ); + + int dxi_list( char *who, char *ans ) + { + int len; + extern char *dxi_buffer; + extern int dxi_errno; + extern int dxi_limitiserror; + + strcpy( dxi_buffer, who ); + len = strlen( who ) + 1; + + /* and now ship it */ + if ( dxi_send( DXI_LIST, dxi_buffer, len, ans, MAX_PKT_SIZE, 0 ) + == -1 ) { + dxi_errno = DXI_DOWN; + return( -1 ); + } + dxi_errno = ans[DXI_H_RC]; + + if ( dxi_limitiserror ) + return( dxi_errno == DXI_SUCCESS ? 0 : -1 ); + else + return( dxi_errno == DXI_SUCCESS || dxi_errno == DXI_SIZELIMIT + || dxi_errno == DXI_TIMELIMIT ? 0 : -1 ); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/modify.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/modify.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/modify.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,70 ---- + /* + * Copyright (c) 1990 Regents of the University of Michigan. + * All rights reserved. + * + * mod.c + */ + + #ifndef lint + static char copyright[] = "@(#) Copyright (c) 1990 Regents of the University of Michigan.\nAll rights reserved.\n"; + #endif + + #include + #include "dixie.h" + #include + #include + + extern int dxi_limit; + extern char *dxi_buffer; + extern int dxi_errno; + extern int dxi_debug; + extern int dxi_bound; + + extern int dxi_send( char type, char *buf, int buflen, char *answer, int anslen, int scope ); + + /* + * dxi_modify - do a dixie (x.500) modify operation. Who contains the DN + * of the entry to modify, what contains null-terminated array of char * + * changes to make, each of which has one of the following forms: + * attribute : delete attribute + * attribute=value : make value the sole value for attribute + * attribute+=value : add value to attribute + * attribute-=value : remove value from attribute + * value can specify multiple values by separating them with &'s. + * + * Example: + * char *changes[] = { "cn+=bob", "mail-=fred at bob.edu", 0 }; + * dxi_modify( "c=us at cn=bob", changes ); + */ + + int dxi_modify( char *who, char **what ) + { + int i, rc, len; + char *tmp; + char answer[ DXI_H_SIZE + 1 ]; + + /* we need to be talking over TCP */ + if ( dxi_bound < 0 ) { + dxi_errno = DXI_NOTCONN; + return( -1 ); + } + + strcpy( dxi_buffer, who ); + len = strlen( dxi_buffer ) + 1; + tmp = dxi_buffer + len; + for ( i = 0; what[i] != NULL; i++ ) { + strcpy( tmp, what[i] ); + len += strlen( what[i] ) + 1; + tmp = dxi_buffer + len; + } + + /* ship it */ + if ( (rc = dxi_send( DXI_WRITE, dxi_buffer, len, answer, + sizeof(answer), 0 )) < 0 ) { + dxi_errno = DXI_DOWN; + return( rc ); + } + dxi_errno = answer[DXI_H_RC]; + + return( dxi_errno == DXI_SUCCESS ? 0 : -1 ); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/modrdn.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/modrdn.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/modrdn.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,49 ---- + /* + * Copyright (c) 1990 Regents of the University of Michigan. + * All rights reserved. + * + * modrdn.c + */ + + #ifndef lint + static char copyright[] = "@(#) Copyright (c) 1990 Regents of the University of Michigan.\nAll rights reserved.\n"; + #endif + + #include "dixie.h" + #include + #include + + /* + * dxi_modrdn - do a dixie (X.500) modrdn operation. The DN of the entry to + * modrdn is supplied (in text form), along with the new RDN. + * + * Example: + * dxi_modrdn( "c=us at cn=bob", "cn=fred" ) + */ + + extern int dxi_send( char type, char *buf, int buflen, char *answer, int anslen, int + scope ); + + int dxi_modrdn( char *who, char *newrdn ) + { + int len; + char *tmp, ans[ DXI_H_SIZE + 1 ]; + extern char *dxi_buffer; + extern int dxi_errno; + + strcpy( dxi_buffer, who ); + len = strlen( who ) + 1; + tmp = dxi_buffer + len; + strcpy( tmp, newrdn ); + len += strlen( newrdn ) + 1; + + /* ship it */ + if ( dxi_send( DXI_MODRDN, dxi_buffer, len, ans, sizeof(ans), 0 ) + == -1 ) { + dxi_errno = DXI_DOWN; + return( -1 ); + } + dxi_errno = ans[DXI_H_RC]; + + return( dxi_errno == DXI_SUCCESS ? 0 : -1 ); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/parse.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/parse.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/parse.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,400 ---- + /* + * Copyright (c) 1990 Regents of the University of Michigan. + * All rights reserved. + * + * show.c + */ + + #ifndef lint + static char copyright[] = "@(#) Copyright (c) 1990 Regents of the University of Michigan.\nAll rights reserved.\n"; + #endif + + #include "dixie.h" + #include + #include + #include + #include + #if !defined(__STDC__) && !defined(VMS) + #include + #endif + #if !defined(MACOS) & !defined(NeXT) & !defined(DOS) + #include + #include + #endif /* MACOS NeXT DOS */ + + extern int dxi_send( char type, char *buf, int buflen, char *answer, int anslen, int scope); + + static char *dxi_current; + static char dxi_attr[ 64 ]; + + #ifdef VMS + + long strncasecmp( char * string1, char * string2, unsigned long maxlen ) + { + char copystring1[256], copystring2[256]; + long i; + + strncpy (copystring1, string1, 256); + strncpy (copystring2, string2, 256); + + i = 0; + while ((i < 256) && (copystring1[i] != '\0')) + { + toupper (copystring1[i]); + i++; + }; + i = 0; + while ((i < 256) && (copystring2[i] != '\0')) + { + toupper (copystring2[i]); + i++; + }; + return (strncmp (copystring1, copystring2, maxlen)); + } + + long strcasecmp( char * string1, char * string2) + { + return (strncasecmp (string1, string2, 256)); + } + + #endif + + char *dxi_findtype( char *buf, char *at ) + { + char *p, *s, save; + + s = p = buf; + while ( 1 ) { + while ( *s != DXI_ATR_SEP && *s != DXI_DNS_SEP && *s != '\0' ) + s++; + if ( *s == '\0' || *s == DXI_DNS_SEP ) + break; + s++; + + p = s; + while ( *s != DXI_VAL_SEP && *s != DXI_ATR_SEP + && *s != DXI_DNS_SEP && *s != '\0' ) + s++; + if ( *s == '\0' ) + break; + + save = *s; + *s = '\0'; + + if ( strcasecmp( at, p ) == 0 ) { + *s = save; + return( p ); + } + + *s = save; + } + + return( NULL ); + } + + char *dxi_firstattr( char *ent ) + { + char *p, *a; + + for ( p = ent; *p != DXI_ATR_SEP && *p != '\0'; p++ ) + ; /* NULL */ + + if ( *p == '\0' || *++p == DXI_DNS_SEP || *p == '\0' ) + return( NULL ); + + a = dxi_attr; + while ( *p != DXI_VAL_SEP && *p != DXI_ATR_SEP && *p != DXI_DNS_SEP ) + *a++ = *p++; + *a = '\0'; + + return( dxi_attr ); + } + + char *dxi_nextattr( char *attr ) + { + char *p, *a; + + if ( (p = dxi_findtype( dxi_current, attr )) == NULL ) + return( NULL ); + + while ( *p != DXI_ATR_SEP && *p != DXI_DNS_SEP && *p != '\0' ) + p++; + + if ( *p == '\0' || *p++ == DXI_DNS_SEP ) + return( NULL ); + + a = dxi_attr; + while ( *p != DXI_VAL_SEP && *p != DXI_ATR_SEP && *p != DXI_DNS_SEP ) + *a++ = *p++; + *a = '\0'; + + return( dxi_attr ); + } + + int dxi_matches( char *buf ) + { + short matches; + + if ( buf[DXI_H_RC] != DXI_SUCCESS && buf[DXI_H_RC] != DXI_SIZELIMIT + && buf[DXI_H_RC] != DXI_TIMELIMIT ) + return( 0 ); /* no matches */ + else if ( buf[DXI_H_SIZE + 1] != DXI_DNS_SEP && buf[DXI_H_SIZE + 2] + != DXI_DNS_SEP ) + if ( buf[DXI_H_SIZE + 2] == 0 ) + return( 0 ); /* no matches */ + else + return( 1 ); /* read result - one match */ + else if ( buf[DXI_H_VERSION] == 0 ) + return( buf[DXI_H_SIZE] ); /* search result */ + else { + short tmp; + + (void) memcpy( (char *) &tmp, &buf[DXI_H_SIZE], sizeof(short) ); + matches = ntohs( tmp ); + return( matches ); + } + } + + int dxi_countvalues( char *avl ) + { + int num = 0; + + while ( *avl && *avl != DXI_ATR_SEP && *avl != DXI_DNS_SEP ) + if ( *avl++ == DXI_VAL_SEP ) num++; + + return( num ); + } + + char *dxi_firstentry( char *buf ) + { + if ( buf[DXI_H_RC] != DXI_SUCCESS && buf[DXI_H_RC] != DXI_LIMIT + && buf[DXI_H_RC] != DXI_TIMELIMIT + || buf[DXI_H_SIZE + 2] == 0 ) + return( 0 ); /* no entries */ + if ( buf[DXI_H_SIZE + 2] == DXI_DNS_SEP ) + return( dxi_current = &buf[DXI_H_SIZE + 3] ); + else if ( buf[DXI_H_SIZE + 1] == DXI_DNS_SEP ) + return( dxi_current = &buf[DXI_H_SIZE + 2] ); + else + return( dxi_current = &buf[DXI_H_SIZE] ); + } + + char *dxi_getreadentry( char *buf ) + { + if ( buf[DXI_H_RC] != DXI_SUCCESS && buf[DXI_H_RC] != DXI_LIMIT + && buf[DXI_H_RC] != DXI_TIMELIMIT + || buf[DXI_H_SIZE + 2] == 0 ) + return( 0 ); /* no entries */ + if ( buf[DXI_H_SIZE + 2] == DXI_DNS_SEP ) + return( &buf[DXI_H_SIZE + 3] ); + else if ( buf[DXI_H_SIZE + 1] == DXI_DNS_SEP ) + return( &buf[DXI_H_SIZE + 2] ); + else + return( &buf[DXI_H_SIZE] ); + } + + char *dxi_nextentry(void) + { + dxi_current = strchr( dxi_current, DXI_DNS_SEP ); + return( dxi_current ? ++dxi_current : NULL ); + } + + char *dxi_getdn( char *buf ) + { + char *result, *p, save; + + for ( p = buf; *p && *p != DXI_ATR_SEP && *p != DXI_DNS_SEP; p++ ) + ; /* NULL */ + + save = *p; + *p = '\0'; + result = (char *) strdup( buf ); + *p = save; + + return( result ); + } + + char **dxi_getvalues( char *buf, char *at ) + { + char *p, *s, save; + char **av; + int num, i; + + if ( (p = dxi_findtype( buf, at )) == NULL ) + return( (char **) 0 ); + + if ( (num = dxi_countvalues( p )) == 0 ) + return( (char **) 0 ); + + if ( (av = (char **) calloc( num + 1, sizeof(char *) )) == (char **) 0 ) + return( (char **) 0 ); + + p = strchr( p, DXI_VAL_SEP ) + 1; + for ( i = 0; i < num; i++ ) { + s = p; + while ( *s && *s != DXI_VAL_SEP && *s != DXI_ATR_SEP + && *s != DXI_DNS_SEP ) + s++; + save = *s; + *s = '\0'; + + if ( *p == DXI_ATEND_FLAG ) { + char *last; + unsigned long len; + + /* + * find the end of the packet - what we want should + * be just after that + */ + + last = strchr( s + 1, '\0' ); + last++; + + (void) memcpy( (char *) &len, last, sizeof(len) ); + + if ( (av[i] = (char *) malloc( len + 4 )) == NULL ) + return( (char **) 0 ); + + (void) memcpy( av[i], last, len + 4 ); + } else { + av[i] = (char *) strdup( p ); + if ( dxi_not61 ) + dxi_det61( av[i] ); + } + + *s = save; + p = s + 1; + } + av[num] = NULL; + + return( av ); + } + + void dxi_valuefree( char **av ) + { + int i; + + if ( av == (char **) 0 ) + return; + + for ( i = 0; av[i] != NULL; i++ ) + free( av[i] ); + free( av ); + } + + char *dxi_lastdncomp( char *dn ) + { + char *p; + + if ( (p = strrchr( dn, '@' )) == NULL ) + p = dn; + + while ( *p && *p != '=' ) p++; + + return( ++p ); + } + + #ifdef DOS + /* for some reason, this wasn't working in dos, so we write our own! */ + static char *mystrcat( char *a, char *b ) + { + char *save = a; + + while ( *a ) + a++; + + while ( *a++ = *b++ ) + ; /* NULL */ + + return( save ); + } + #endif + + /* + * dxi_dn2ufn returns the ufn representation of dn. dn may be trashed. + */ + + char *dxi_dn2ufn( char *dn ) + { + char *p; + int first; + static char buf[512]; + + buf[0] = '\0'; + first = 1; + while ( (p = strrchr( dn, '=' )) != NULL ) { + if ( first == 0 ) + #ifdef DOS + mystrcat( buf, ", " ); + #else + strcat( buf, ", " ); + #endif + else + first = 0; + + #ifdef DOS + mystrcat( buf, p + 1 ); + #else + strcat( buf, p + 1 ); + #endif + + if ( (p = strrchr( dn, '@' )) != NULL ) + *p = '\0'; + else + break; + } + + return( buf ); + } + + #define T61 "{T.61}" + #define T61LEN 6 + + void dxi_det61( char *s ) + { + char *next = s; + int c, hex; + + while ( *s ) { + switch ( *s ) { + case '{' : + if ( strncasecmp( s, T61, T61LEN) == 0 ) { + s += T61LEN; + } else { + *next++ = *s++; + } + break; + + case '\\': + c = *(s + 1); + if ( c == '\n' ) { + s++; + *next++ = *s++; + break; + } + if ( isdigit( c ) ) + hex = c - '0'; + else if ( isupper( c ) ) + hex = c - 'A' + 10; + else + hex = c - 'a' + 10; + hex <<= 4; + c = *(s + 2); + if ( isdigit( c) ) + hex += c - '0'; + else if ( isupper( c ) ) + hex += c - 'A' + 10; + else + hex += c - 'a' + 10; + + *next++ = hex; + s += 3; + break; + + default: + *next++ = *s++; + break; + } + } + *next = '\0'; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/read.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/read.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/read.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,68 ---- + /* + * Copyright (c) 1990 Regents of the University of Michigan. + * All rights reserved. + * + * show.c + */ + + #ifndef lint + static char copyright[] = "@(#) Copyright (c) 1990 Regents of the University of Michigan.\nAll rights reserved.\n"; + #endif + + #include + #include "dixie.h" + #include + + extern int dxi_send( char type, char *buf, int buflen, char *answer, int anslen, int scope ); + + + /* + * dxi_read - do a dixie (X.500) read operation. The DN of the entry to + * read is supplied (in text form), along with the attributes to read + * (in attrs). Attrs is a null-terminated array of attribute types to + * be returned, NULL if all attrs are wanted. The result of the read + * is passed back in ans, which should point to enough space. + * + * Example: + * char *attrs[] = { "cn", "sn", "mail", 0 }; + * dxi_read( "c=us at cn=bob", attrs, answerbuffer ) + */ + + int dxi_read( char *who, char **attrs, char *ans ) + { + int i, len; + extern char *dxi_buffer; + extern int dxi_errno; + + if ( attrs == NULL ) { + strcpy( dxi_buffer, who ); + len = strlen( who ); + dxi_buffer[len++] = '\0'; + dxi_buffer[len++] = '\0'; + } else { + strcpy( dxi_buffer, who ); + len = strlen( who ); + for ( i = 0; attrs[i] != NULL; i++ ) { + dxi_buffer[len++] = DXI_VAL_SEP; + dxi_buffer[len] = '\0'; + strcat( dxi_buffer, attrs[i] ); + len += strlen( attrs[i] ); + } + for ( i = 0; i < len; i++ ) { + if ( dxi_buffer[i] == DXI_VAL_SEP ) + dxi_buffer[i] = '\0'; + } + dxi_buffer[++len] = '\0'; + len++; + } + + /* and now ship it */ + if ( (i = dxi_send( DXI_READ, dxi_buffer, len, ans, MAX_PKT_SIZE, 0 )) + == -1 ) { + dxi_errno = DXI_DOWN; + return( -1 ); + } + dxi_errno = ans[DXI_H_RC]; + + return( dxi_errno == DXI_SUCCESS ? 0 : -1 ); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/remove.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/remove.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/remove.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,45 ---- + /* + * Copyright (c) 1990 Regents of the University of Michigan. + * All rights reserved. + * + * remove.c + */ + + #ifndef lint + static char copyright[] = "@(#) Copyright (c) 1990 Regents of the University of Michigan.\nAll rights reserved.\n"; + #endif + + #include + #include "dixie.h" + #include + + extern int dxi_send( char type, char *buf, int buflen, char *answer, int anslen, int scope ); + + /* + * dxi_remove - do a dixie (X.500) remove operation. The DN of the entry to + * remove is supplied (in text form). + * + * Example: + * dxi_remove( "c=us at cn=bob" ) + */ + + int dxi_remove( char *who ) + { + int len; + char ans[ DXI_H_SIZE + 1 ]; + extern char *dxi_buffer; + extern int dxi_errno; + + strcpy( dxi_buffer, who ); + len = strlen( dxi_buffer ) + 1; + + /* ship it */ + if ( dxi_send( DXI_REMOVE, dxi_buffer, len, ans, sizeof(ans), 0 ) + == -1 ) { + dxi_errno = DXI_DOWN; + return( -1 ); + } + dxi_errno = ans[DXI_H_RC]; + + return( dxi_errno == DXI_SUCCESS ? 0 : -1 ); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/search.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/search.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/search.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,79 ---- + /* + * Copyright (c) 1990 Regents of the University of Michigan. + * All rights reserved. + * + * search.c + */ + + #ifndef lint + static char copyright[] = "@(#) Copyright (c) 1990 Regents of the University of Michigan.\nAll rights reserved.\n"; + #endif + + #include + #include + #include "dixie.h" + #include + + extern int dxi_send( char type, char *buf, int buflen, char *answer, int anslen, int scope ); + + /* + * dxi_search - do a dixie (X.500) search operation. Parameters are + * base: text form of the DN to start the search at + * scope: the search scope (see dixie.h) + * filter: a string containing the filter (e.g., cn~=bob) + * attrlist: list of attribute types to return for matches + * answer: buffer where the result will be placed + * + * Example: + * char *attrs[] = { "mail", "title", 0 }; + * dxi_search( "c=us at o=university of michigan", DXI_SRCH_SUBTREE, + * "cn~=bob", attrs, answerbuffer ) + */ + + int dxi_search( char *base, int scope, char *filter, char *attrlist[], char *answer ) + { + int i, len, rc; + extern char *dxi_buffer; + extern int dxi_errno; + extern int dxi_limitiserror; + + dxi_errno = DXI_SUCCESS; + + strcpy( dxi_buffer, base ); + len = strlen( base ); + dxi_buffer[len++] = DXI_VAL_SEP; + dxi_buffer[len] = '\0'; + strcat( dxi_buffer, filter ); + len += strlen( filter ); + if ( attrlist == NULL ) { + dxi_buffer[len++] = '\0'; + } else { + for ( i = 0; attrlist[i] != NULL; i++ ) { + dxi_buffer[len++] = DXI_VAL_SEP; + dxi_buffer[len] = '\0'; + strcat( dxi_buffer, attrlist[i] ); + len += strlen( attrlist[i] ); + } + dxi_buffer[++len] = '\0'; + } + for ( i = 0; i < len; i++ ) { + if ( dxi_buffer[i] == DXI_VAL_SEP ) + dxi_buffer[i] = '\0'; + } + + /* ship it */ + if ( (rc = dxi_send( DXI_SEARCH_GEN, dxi_buffer, len, answer, + MAX_PKT_SIZE, scope )) < 0 ) { + dxi_errno = DXI_DOWN; + return( rc ); + } + + dxi_errno = answer[DXI_H_RC]; + if ( dxi_limitiserror ) + return( dxi_errno == DXI_SUCCESS || dxi_errno == DXI_NOTFOUND + ? 0 : -1 ); + else + return( dxi_errno == DXI_SUCCESS || dxi_errno == DXI_SIZELIMIT + || dxi_errno == DXI_TIMELIMIT || dxi_errno == DXI_NOTFOUND + ? 0 : -1 ); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/send.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/send.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/send.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,500 ---- + /* + * Copyright (c) 1990 Regents of the University of Michigan. + * All rights reserved. + * + * send.c + */ + + #ifndef lint + static char copyright[] = "@(#) Copyright (c) 1990 Regents of the University of Michigan.\nAll rights reserved.\n"; + #endif + + #include + #include + #include "dixie.h" + #include + #if !defined(__STDC__) && !defined(VMS) + #include + #endif + #if defined(MACOS) + #include "tcp.h" + #else + #ifdef VMS + #include + #include + #include + #else + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #endif + + #define MAX_RETRY 3 + #define MAX_DIXIE_SERVERS 5 + + #define DXI_GETLEN(x, y) { (void) memcpy( (char *) &x, &y[DXI_H_TOTLEN], \ + sizeof(long)); x = ntohl(x);} + #define DXI_GETID(x, y) { (void) memcpy( (char *) &x, &y[DXI_H_ID], \ + sizeof(short));} + #define DXI_SETID(x, y) { (void) memcpy( (char *) &y[DXI_H_ID], (char *) &x, \ + sizeof(short));} + #define DXI_SETOP(x, y) { (void) memcpy( (char *) &y[DXI_H_OP], (char *) &x, \ + sizeof(short));} + #define DXI_SETSCOPE(x, y) {y[DXI_H_SRCH_SCOPE] = x;} + #define DXI_SETVERSION(x, y) {y[DXI_H_VERSION] = x;} + #define DXI_SETOPTIONS(x, y) {y[DXI_H_OPTIONS] = x;} + #define DXI_SETTIMELIMIT(x, y) { (void) memcpy( &y[DXI_H_TIMELIMIT], \ + (char *) &x, sizeof(short));} + #define DXI_SETSIZELIMIT(x, y) { (void) memcpy( &y[DXI_H_SIZELIMIT], \ + (char *) &x, sizeof(short));} + + extern void *memset(void *s, int c, size_t n); + extern int errno, dxi_debug, dxi_timeout, dxi_retries; + extern char dxi_options; + + #ifndef INADDR_LOOPBACK + #define INADDR_LOOPBACK 0x7f000001 + #endif + + #ifndef FD_SET + #define NFDBITS 32 + #define FD_SETSIZE 32 + #define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS))) + #define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS))) + #define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS))) + #define FD_ZERO(p) (void) memset((char *)(p), 0, sizeof(*(p))) + #endif + + #ifndef VMS + char *h_errlist[] = { + "Error 0", + "Unknown host", /* 1 HOST_NOT_FOUND */ + "Host name lookup failure", /* 2 TRY_AGAIN */ + "Unknown server error", /* 3 NO_RECOVERY */ + "No address associated with name", /* 4 NO_ADDRESS */ + }; + #endif + + static int s = -1; /* socket used for UDP */ + #if defined(MACOS) || defined(DOS) + ip_addr dixieaddr; /* address of dixie server */ + #else + void attempt_rebind(); + struct sockaddr_in dixieaddr; /* address of dixie server */ + extern int nullbound; + #endif + static int servers; + static char *dxibuf; + + #if !defined(NOUDP) && !defined(VMS_MULTINET) + int xres_selwait(int sock, struct timeval *timeout) + { + fd_set dsmask; + register int n; + + FD_ZERO(&dsmask); + FD_SET(sock, &dsmask); + n = select(sock+1, &dsmask, (fd_set *)NULL, (fd_set *)NULL, timeout); + return(n); + } + #endif /* !NOUDP & !vms_multinet */ + + int dxi_send( char type, char *buf, int buflen, char *answer, int anslen, int scope ) + { + int i, n; + int retry; + long resplen, totlen; + short nshort; + #ifndef NOUDP + struct timeval timeout; + #endif + static unsigned short id = 0; + extern int dxi_bound; + + if ( dxibuf == NULL ) + dxibuf = (char *) calloc( MAX_PKT_SIZE + DXI_H_SIZE, 1 ); + + /* + * First, we need to take the buffer we were given and the type + * that was specified and build a valid packet. The query type + * should be put in the first byte of the header, which should + * then be padded out with zeroes. + * + * Then update the buffer size to reflect the addition of the + * header and point buffer to the newly formed packet. + */ + + bzero(dxibuf, DXI_H_SIZE); + DXI_SETOP(type, dxibuf); + DXI_SETSCOPE(scope, dxibuf); + DXI_SETVERSION(1, dxibuf); + DXI_SETOPTIONS(dxi_options, dxibuf); + DXI_SETTIMELIMIT(dxi_timelimit, dxibuf); + DXI_SETSIZELIMIT(dxi_sizelimit, dxibuf); + (void) memcpy(&dxibuf[DXI_H_SIZE], buf, buflen); + buflen += DXI_H_SIZE; + buf = dxibuf; + + /* use the default DIXIE server if none defined */ + if (servers == 0) + add_server(INADDR_LOOPBACK); + id++; + nshort = htons(id); + + /* if bound to a DSA use our open TCP socket */ + if (dxi_bound >= 0) { + (void) memcpy( &buf[DXI_H_ID], (char *) &nshort, sizeof(short)); + (void) memset( answer, 0, DXI_H_SIZE ); + #ifdef DEBUG + if (dxi_debug > 5) { + printf("Sending (%d) over TCP:\n", buflen); + dxi_bprint(buf, buflen); + } + #endif + + #if defined(DOS) || defined(MACOS) || defined VMS_MULTINET + #ifdef DOS + if ( netwrite( dxi_bound, (u_char *) buf, buflen ) < 0 ) { + return( -1 ); + } + if ( (resplen = nread( dxi_bound, answer, anslen )) < 0 ) { + return( -1 ); + } + #else /* macos or vms */ + #ifdef MACOS + if (tcpwrite(dxi_bound, (u_char *)buf, buflen ) != 0 ) { + return(-1); + } + if ((resplen = tcpread(dxi_bound, 0, (u_char *)answer, anslen, (DialogPtr)NULL )) < 0 ) { + return( -1 ); + } + #else /* vms */ + while (TRUE) + { + if (socket_write(dxi_bound, buf, buflen) != buflen) + if (socket_errno == EWOULDBLOCK) + { + continue; + } + else + { + socket_perror("write"); + return(-1); + }; + break; + } + while (TRUE) + { + if ((resplen = socket_read(dxi_bound, answer, anslen)) < 0) + if (socket_errno == EWOULDBLOCK) + { + continue; + } + else + { + socket_perror("read"); + return(-1); + }; + break; + } + #endif /* vms */ + #endif /* macos or vms */ + #else /* unix */ + for ( i = 0; i < 2; i++ ) { + if (write(dxi_bound, buf, buflen) != buflen) { + if ( dxi_bound >= 0 ) + close( dxi_bound ); + dxi_bound = -1; + + if ( ! nullbound ) + return( -1 ); + + (void) dxi_bind( NULL, NULL ); + continue; + } + + if ((resplen = read(dxi_bound, answer, anslen)) <= 0) { + if ( dxi_bound >= 0 ) + close( dxi_bound ); + dxi_bound = -1; + + if ( ! nullbound ) + return( -1 ); + + (void) dxi_bind( NULL, NULL ); + continue; + } + break; + } + + if ( dxi_bound < 0 ) { + return(-1); + } + #endif + DXI_GETLEN( totlen, answer ); + totlen += DXI_H_SIZE; + n = resplen; + if ( dxi_debug > 5 ) printf("totlen is %d\n", totlen ); + while ( resplen < totlen ) { + if ( dxi_debug > 5 ) + printf("...%d to go\n", totlen - resplen); + #if defined(DOS) || defined(MACOS) || defined(VMS_MULTINET) + #ifdef DOS + if ( (n = nread( dxi_bound, answer + resplen, + totlen - n )) < 0 ) { + return( -1 ); + } + #else /* MACOS or VMS_MULTINET */ + #ifdef MACOS + if ((n = tcpread( dxi_bound, 0, (u_char *)answer + resplen, totlen - n, + (DialogPtr)NULL )) < 0 ) { + return( -1 ); + } + #else /* VMS_MULTINET */ + if ( (n = socket_read( dxi_bound, answer + resplen, + totlen - n )) < 0 ) { + socket_perror( "read" ); + return( -1 ); + } + #endif /* MACOS */ + #endif /* MACOS or VMS_MULTINET */ + #else /* UNIX */ + if ( (n = read( dxi_bound, answer + resplen, + totlen - n )) <= 0 ) { + perror( "read" ); + return( -1 ); + } + #endif + if ( dxi_debug > 5 ) + printf("...read %d\n", n ); + resplen += n; + } + #ifdef DEBUG + if (dxi_debug > 5) { + printf("Received (%d):\n", resplen); + dxi_bprint(answer, resplen); + } + #endif + return(resplen); + } + + /* + * OK, we weren't bound, so we'll need to use UDP. + */ + #ifndef NOUDP + + /* Get a socket if we don't already have one */ + if ( s < 0 ) { + if ( (s = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 ) { + perror( "socket" ); + return( -1 ); + } + } + + DXI_SETID( nshort, buf ); + (void) memset( answer, 0, DXI_H_SIZE ); + timeout.tv_sec = 0; + timeout.tv_usec = 0; + for ( retry = 0; retry < dxi_retries; retry++ ) { + #ifdef DEBUG + if ( dxi_debug & 4 ) { + printf("Sending (%d) try #%d:\n", buflen, retry); + dxi_bprint( buf, buflen ); + } + #endif + if ( sendto( s, buf, buflen, 0, (struct sockaddr *)&dixieaddr, + sizeof(struct sockaddr)) < 0 ) { + perror( "sendto" ); + return( -1 ); + } + + /* wait for a reply (exponential back off) */ + timeout.tv_sec = timeout.tv_sec == 0 ? dxi_timeout + : 2 * timeout.tv_sec; + timeout.tv_usec = 0; + + wait: + #ifndef VMS_MULTINET + if ( (n = xres_selwait( s, &timeout )) < 0 ) { + perror( "xres_selwait" ); + continue; + } + + /* timed out */ + if (n == 0) + continue; + + /* didn't timeout -- read the packet */ + if ( (resplen = recv( s, answer, anslen, 0 )) < 0 ) { + perror( "recv" ); + return( -1 ); + } + #endif + #ifdef DEBUG + if ( dxi_debug & 4 ) { + printf("Received (%d):\n", resplen); + dxi_bprint( answer, resplen ); + } + #endif + /* + * Fetch out the id, convert it to host order + * and see if its in response to the current request. + */ + + DXI_GETID( nshort, answer ); + if ( id != (nshort = ntohs(nshort)) ) { + if ( dxi_debug & 4 ) + printf("expecting id %d got %d\n", id, nshort); + goto wait; + } + + DXI_GETLEN( totlen, answer ); + if ( totlen + DXI_H_SIZE != resplen ) { + answer[DXI_H_RC] = DXI_TOOBIG; + return( DXI_H_SIZE ); + } + + return( resplen ); + } + + if (s >= 0) { + #ifdef VMS_MULTINET + (void) socket_close( s ); + #else + (void) close( s ); + #endif /* vms */ + s = -1; + } + #ifdef VMS_MULTINET + socket_errno = ETIMEDOUT; + #else + errno = ETIMEDOUT; + #endif /* vms */ + #endif + + return (-1); + } + + #if defined(MACOS) || defined(DOS) + int open_sock(unsigned long address, short port) + { + short s; + + if (( s = tcpopen( NULL, TCP_BUFSIZ )) < 0 ) { + return( s ); + } + + if ( tcpconnect( s, address, port ) < 0 ) { + return( -1 ); + } + + return( s ); + } + #else + int open_sock( unsigned long address, int port ) + { + int s; + struct sockaddr_in sock; + + sock.sin_addr.s_addr = htonl( address ); + sock.sin_family = AF_INET; + sock.sin_port = htons( port ); + if ( (s = socket( AF_INET, SOCK_STREAM, 0 )) < 0 ) { + dxi_errno = DXI_ERROR; + return( s ); + } + if ( connect( s, (struct sockaddr *) &sock, sizeof(sock) ) < 0 ) { + dxi_errno = DXI_DOWN; + return( -1 ); + } + if (dxi_debug) printf("open_sock returning %d\n", s); + return( s ); + } + #endif + + int add_server( u_long ns ) + { + #if !defined(MACOS) & !defined(DOS) + struct hostent *hp; + struct servent *sp; + struct in_addr in; + extern int h_errno; + #endif + int port; + + /* give up if earlier routines failed */ + if ( ns == 0 ) return( -1 ); + + /* DIXIE port? */ + #if defined(MACOS) || defined(DOS) + port = DXI_PORT; + dixieaddr = ns; + #else + if ( (sp = getservbyname( "dixie", "udp" )) == NULL ) + port = DXI_PORT; + else + port = sp->s_port; + in.s_addr = ns; + + /* add the new server */ + hp = gethostbyaddr( (char *) &in, sizeof(in), AF_INET ); + if ( hp == NULL && h_errno != TRY_AGAIN ) { + return( -1 ); + } + dixieaddr.sin_addr.s_addr = htonl( ns ); + dixieaddr.sin_family = AF_INET; + dixieaddr.sin_port = htons( port ); + #endif + servers = 1; + + return( 0 ); + } + + + int dxi_close(void) + { + extern int dxi_bound; + + if (dxi_bound >= 0) { + #ifndef NOUDP + if ( s >= 0 ) { /* close UDP socket */ + close( s ); + s = -1; + } + #endif + + #if defined(MACOS) || defined(DOS) + tcpclose( dxi_bound ); /* close TCP socket */ + #else + close( dxi_bound ); /* close TCP socket */ + #endif + } + + if (dxi_debug) printf("**** dxi_close ****\n"); + dxi_bound = -1; + if ( dxibuf != NULL ) { /* free the message buffer */ + free( dxibuf ); + dxibuf = NULL; + } + return -99; + } + + #if !defined(MACOS) && !defined(DOS) + + void attempt_rebind(void) + { + + } + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/test.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/test.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/test.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,297 ---- + #include + #include + #include + #include "dixie.h" + #include + #if !defined(__STDC__) && !defined(VMS) + #include + #endif + #if defined(MACOS) || defined(DOS) + #include + #include + #endif + + extern char *dxi_dn2ufn( char *dn ); + + static char *getlinex( char *line, int len, FILE *s, char *prompt ) + { + printf(prompt); + + if ( fgets( line, len, s ) == NULL ) { + dxi_close(); + exit( 0 ); + } + + line[ strlen( line ) - 1 ] = '\0'; + + return( line ); + } + + static void print_listpacket( char *ans ) + { + char *entry, *dn; + int i; + + if ( (i = dxi_matches( ans )) != -1 ) + printf("%d matches:\n", i); + + for ( entry = dxi_firstentry( ans ); entry != NULL; + entry = dxi_nextentry() ) { + dn = dxi_getdn( entry ); + printf("\t%s\n", dn); + printf("\t(UFN) %s\n", dxi_dn2ufn( dn )); + free( dn ); + } + } + + static void print_packet( char *ans ) + { + char *entry, *at, *dn; + char **av; + int i; + + /* + * step through each attr type in attrs and print the + * corresponding values + */ + + if ( (i = dxi_matches( ans )) != -1 ) + printf("%d matches:\n", i); + + for ( entry = dxi_firstentry( ans ); entry != NULL; + entry = dxi_nextentry() ) { + dn = dxi_getdn( entry ); + printf("\n%s\n", dn); + printf("(UFN) %s\n", dxi_dn2ufn( dn )); + free( dn ); + + for ( at = dxi_firstattr( entry ); at != NULL; + at = dxi_nextattr( at ) ) { + printf("\t%s\n", at); + av = dxi_getvalues( entry, at ); + if ( av == (char **) 0 ) + printf("\t\t*** NO VALUES ***\n"); + else { + if ( strcmp( at, "photo" ) == 0 ) { + unsigned long len; + + (void) memcpy( (char *) &len, av[0], + sizeof(len) ); + printf("\t\t%d bytes of %s photo\n", + len, av[0][4] == DXI_PHOTO_JPEG ? + "JPEG" : "G3Fax"); + } else { + for ( i = 0; av[i] != NULL; i++ ) { + printf("\t\t%s\n", av[i]); + } + } + dxi_valuefree( av ); + } + } + } + } + + static char **get_list( char *prompt ) + { + static char buf[256]; + int num; + char **result; + + num = 0; + result = (char **) 0; + while ( 1 ) { + getlinex( buf, sizeof(buf), stdin, prompt ); + + if ( *buf == '\0' ) + break; + + if ( result == (char **) 0 ) + result = (char **) malloc( sizeof(char *) ); + else + result = (char **) realloc( result, + sizeof(char *) * (num + 1) ); + + result[num++] = (char *) strdup( buf ); + } + if ( result == (char **) 0 ) + return( NULL ); + result = (char **) realloc( result, sizeof(char *) * (num + 1) ); + result[num] = NULL; + + return( result ); + } + + int main( int argc, char **argv ) + { + char *ans; + int alen; + char line[256], command, *lp; + char searchattr[80], attr[180], who[256]; + char new1[80], value[256]; + int genscope; + char **entry; + extern int dxi_debug; + + if (( ans = (char *) malloc( MAX_PKT_SIZE )) == NULL ) { + perror( "malloc" ); + exit(1); + } + #if defined(MACOS) || defined(DOS) + getlinex( line, sizeof(line), stdin, "dixie server? " ); + if ( dxi_init( line, 2, 4 ) != 0 ) { + #else + if ( dxi_init( argc > 1 ? argv[1] : NULL, 2, 4 ) != 0 ) { + #endif + perror( "dxi_init" ); + exit(1); + } + + while ( getlinex( line, sizeof(line), stdin, "\ncommand? " ) != NULL ) { + command = line[0]; + for ( lp = line; *lp && !isspace(*lp); lp++ ) + ; /* NULL */ + + alen = 0; + switch ( command ) { + case 'l': /* list */ + getlinex( who, sizeof(who), stdin, "dn? " ); + + alen = dxi_list( who, ans ); + break; + + case 'r': /* read */ + getlinex( who, sizeof(who), stdin, "dn? " ); + entry = get_list( "attr to return? " ); + + alen = dxi_read( who, entry, ans ); + break; + + case 's': /* search */ + getlinex( who, sizeof(who), stdin, "searchbase? " ); + getlinex( line, sizeof(line), stdin, + "scope (1=Base, 2=One Level, 3=Subtree)?" ); + genscope = atoi( line ); + getlinex( searchattr, sizeof(searchattr), stdin, + "search filter (e.g. sn=jones)? " ); + entry = get_list( "attr to return? " ); + + alen = dxi_search( who, genscope, searchattr, entry, + ans ); + break; + + case 'm': /* modify */ + getlinex( who, sizeof(who), stdin, "dn? " ); + entry = get_list( "modify list? " ); + + alen = dxi_modify( who, entry ); + + dxi_valuefree( entry ); + break; + + case 'a': /* add */ + getlinex( who, sizeof(who), stdin, "dn? " ); + entry = get_list( "attr to return? " ); + + alen = dxi_add( who, entry ); + + dxi_valuefree( entry ); + break; + + case 'v': /* remove */ + getlinex( who, sizeof(who), stdin, "dn? " ); + + alen = dxi_remove( who ); + break; + + case 'c': /* modify rdn */ + getlinex( who, sizeof(who), stdin, "olddn? " ); + getlinex( new1, sizeof(new1), stdin, "newrdn? " ); + + alen = dxi_modrdn( who, new1 ); + break; + + case 'p': /* compare */ + getlinex( who, sizeof(who), stdin, "dn? " ); + getlinex( attr, sizeof(attr), stdin, "attr? " ); + getlinex( value, sizeof(value), stdin, "value? " ); + if ( (alen = dxi_compare( who, attr, value )) == -1 ) + break; + printf("%d\n", alen); + continue; + + case 'u': /* udp bind */ + getlinex( who, sizeof(who), stdin, "dn? " ); + getlinex( line, sizeof(line), stdin, "password? " ); + + alen = dxi_udpbind( who, line ); + break; + + case 'b': /* tcp bind */ + getlinex( who, sizeof(who), stdin, "dn? " ); + if ( who[0] != '\0' ) + getlinex( line, sizeof(line), stdin, + "password? " ); + else + line[0] = '\0'; + + alen = dxi_bind( who, line ); + break; + + case 'd': /* turn on debugging */ + getlinex( line, sizeof(line), stdin, "debug level? " ); + dxi_debug = atoi( line ); + continue; + break; + + case 'o': /* set dxi_options, size & time limits */ + getlinex( line, sizeof(line), stdin, + "options (not61 or s# or t# or #)? " ); + if ( line[0] == 's' ) + dxi_sizelimit = atoi( line + 1 ); + else if ( line[0] == 't' ) + dxi_timelimit = atoi( line + 1 ); + else if ( line[0] == 'n' ) + dxi_not61 = 1; + else + dxi_options = atoi( line ); + continue; + break; + + case 'q': /* quit */ + dxi_close(); + exit( 0 ); + break; + + case '?': /* help */ + printf("Commands: [r]ead, [s]earch, [m]odify, "); + printf("[b]ind, [l]ist, [q]uit, [d]ebug, [?]help\n"); + printf(" [a]dd, remo[v]e, [c]modifyrdn, "); + printf("[u]dpbind [o]ptions [p]compare\n"); + continue; + break; + + default: + printf("Invalid command. Type ? for help.\n"); + continue; + break; + } + + line[ 0 ] = command; + line[ 1 ] = '\0'; + + if ( alen < 0 ) { /* alen < 0 is an error */ + dxi_perror( line ); + } else { /* alen == 0 might be OK */ + if ( dxi_errno != DXI_SUCCESS ) + dxi_perror( line ); + + if ( command == 's' || command == 'r' ) + print_packet( ans ); + else if ( command == 'l' ) + print_listpacket( ans ); + } + } + + dxi_close(); + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/util.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/util.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/util.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,94 ---- + #include "dixie.h" + #include + #if defined(MACOS) || defined(DOS) + #include + #include + #endif + #include + + /* + * Print arbitrary stuff, for debugging. + */ + + #ifdef DEBUG + + #define BPLEN 48 + + void dxi_bprint( char *data, int len ) + { + static char hexdig[] = "0123456789abcdef"; + char out[ BPLEN ]; + int i = 0; + + bzero( out, BPLEN ); + for ( ;; ) { + if ( len < 1 ) { + printf( "\t%s\n", ( i == 0 ) ? "(end)" : out ); + break; + } + + if ( isgraph( (unsigned char)*data )) { + out[ i ] = ' '; + out[ i+1 ] = *data; + } else { + out[ i ] = hexdig[ ( *data & 0xf0 ) >> 4 ]; + out[ i+1 ] = hexdig[ *data & 0x0f ]; + } + i += 2; + len--; + data++; + + if ( i > BPLEN - 2 ) { + printf( "\t%s\n", out ); + bzero( out, BPLEN ); + i = 0; + continue; + } + out[ i++ ] = ' '; + } + } + + #endif + + + #ifndef DOS + + #undef SUNOS3 + #ifdef SUNOS3 + char *strdup( char *p ) + { + char *r; + + r = (char *) malloc( strlen( p ) + 1 ); + strcpy( r, p ); + + return( r ); + } + #endif + + #ifdef NEEDINETADDR + /* + * this implementation works for decimal dot separated strings only! + */ + u_long inet_addr( char *s ) + { + int i; + char *p; + u_long addr; + + addr = 0; + + for ( i = 0; i < 3; ++i ) { + if (( p = strchr( s, '.' )) == NULL ) { + return( 0 ); + } + *p = '\0'; + addr += atoi( s ); + addr <<= 8; + *p = '.'; + } + + return( addr ); + } + #endif + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/version.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/version.c:1.1 *** /dev/null Tue Oct 5 14:30:02 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/dixie/version.c Tue Oct 5 14:29:51 2004 *************** *** 0 **** --- 1,13 ---- + /* + * Copyright (c) 1991 Regents of the University of Michigan. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that this notice is preserved and that due credit is given + * to the University of Michigan at Ann Arbor. The name of the University + * may not be used to endorse or promote products derived from this + * software without specific prior written permission. This software + * is provided ``as is'' without express or implied warranty. + */ + + char Version[] = " DIXIE library 1.1 (Fri Apr 21 16:41:40 EDT 1995)\n\txxzhang at cadenza.rutgers.edu:/a/fac/u23/xxzhang/Mod-test/dixie\n"; From lattner at cs.uiuc.edu Tue Oct 5 14:30:45 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 14:30:45 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/ Message-ID: <200410051930.OAA24506@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 14:30:54 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 14:30:54 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/Makefile fixoutput.c scanner.h stringI.c Message-ID: <200410051930.OAA24522@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput: Makefile added (r1.1) fixoutput.c added (r1.1) scanner.h added (r1.1) stringI.c added (r1.1) --- Log message: This program fixes the output of something. --- Diffs of the changes: (+462 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/Makefile:1.1 *** /dev/null Tue Oct 5 14:30:53 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/Makefile Tue Oct 5 14:30:43 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = fixoutput + #STDIN_FILENAME = $(SourceDir)/testset + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/fixoutput.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/fixoutput.c:1.1 *** /dev/null Tue Oct 5 14:30:54 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/fixoutput.c Tue Oct 5 14:30:43 2004 *************** *** 0 **** --- 1,320 ---- + + #include "scanner.h" /* Useful Macro Definitions */ + #include + + /* File I/O Variables and Functions in file stringIO.c */ + extern char CH; /* current input character */ + extern char *LEXEME; /* string read in since the last flush */ + + extern char *FRONT,*BACK; /* FRONT: pointer to current input character in + LEXEME. + BACK: pointer to the first input character in + LEXEME, in fact equal to LEXEME */ + extern unsigned LEX_LEN; /* current size of LEXEME buffer. Will change. */ + + extern void FLUSH(); /* a function that sets LEXEME to null */ + extern void GETCHR(); /* a function that gets the next character and + updates LEXEME,FRONT,and BACK appropriately */ + extern void BACKUP(); /* a function that undoes the last not undone + GETCHR */ + + static EOF_FLAG = 1, ERROR_CNT = 0; /* End Of File Flag and ERROR CouNT */ + + static void GETSTR(void) /* read in a string from the input stream */ + { + GETCHR(); + if (CH == ' ') { + FLUSH(); + GETCHR(); + } + else { + ERROR_CNT ++; + printf("------------>ERROR: Expected a SPACE between Token Code and\n"); + printf(" the string following it <--------\n"); + } + while (CH != '\n' && CH != EOF) GETCHR(); + if (CH == '\n') + BACKUP(); + else + EOF_FLAG = 0; + } + + void main(void) + { + int CODE; /* TOKEN CODE */ + int I1,I2; /* temp storage */ + double D1; /* temp storage */ + /* intialization */ + LEXEME = (char *) calloc(LEX_LEN,1); + FLUSH(); + + /* main */ + while (EOF_FLAG) { + scanf("%d",&CODE); + + if (!feof(stdin)) { + switch (CODE) { + + case ERRORMSG_1: + GETSTR(); + printf("Scanner ERROR: %s\n",LEXEME); + break; + + case LINE_1: + scanf("%d",&I1); + printf("===================> LINE NUMBER: %d\n",I1); + break; + + case ADDOP_1: + scanf("%d",&I1); + printf(" ADDOP: "); + switch (I1) { + case PLUS_1: + printf("+\n"); + break; + case MINUS_1: + printf("-\n"); + break; + case OR_1: + printf("OR\n"); + break; + default: { + ERROR_CNT ++; + printf("---------->ERROR: Expected an ADDOP Found: %d\n",I1); + } + } + break; + + case MULOP_1: + scanf("%d",&I1); + printf(" MULOP: "); + switch (I1) { + case TIMES_1: + printf("*\n"); + break; + case SLASH_1: + printf("/\n"); + break; + case AND_1: + printf("AND\n"); + break; + case DIV_1: + printf("DIV\n"); + break; + default: { + ERROR_CNT ++; + printf("---------->ERROR: Expected an MULOP Found: %d\n",I1); + } + } + break; + + case RELOP_1: + scanf("%d",&I1); + printf(" RELOP: "); + switch (I1) { + case EQUAL_1: + printf("=\n"); + break; + case NOTEQUAL_1: + printf("<>\n"); + break; + case LESSTHANOREQUAL_1: + printf("<=\n"); + break; + case LESSTHAN_1: + printf("<\n"); + break; + case GREATERTHANOREQUAL_1: + printf(">=\n"); + break; + case GREATERTHAN_1: + printf(">\n"); + break; + default: { + ERROR_CNT ++; + printf("---------->ERROR: Expected an RELOP Found: %d\n",I1); + } + } + break; + + case ASSIGN_1: + printf(" ASSIGN (:=) \n"); + break; + + case COLON_1: + printf(" COLON (:) \n"); + break; + + case DOTDOT_1: + printf(" DOTDOT (..) \n"); + break; + + case DOT_1: + printf(" DOT (.) \n"); + break; + + case INTEGER_NUMBER_1: + scanf("%d",&I1); + printf(" Integer: "); + if (I1 == ILLEGAL_1) + printf("illegal\n"); + else + if (I1 == VALID_1) { + scanf("%d",&I2); + printf("%d\n",I2); + } + else { + ERROR_CNT ++; + printf("---------->ERROR: Expected a VALID/ILLEGAL Code \n"); + printf(" found: %d\n",I1); + } + break; + + case REAL_NUMBER_1: + scanf("%d",&I1); + printf(" Real: "); + if (I1 == ILLEGAL_1) + printf("illegal\n"); + else + if (I1 == VALID_1) { + scanf("%lf",&D1); + printf("%g\n",D1); + } + else { + ERROR_CNT ++; + printf("---------->ERROR: Expected a VALID/ILLEGAL Code \n"); + printf(" found: %d\n",I1); + } + break; + + case PROGRAM_1: + printf(" PROGRAM \n"); + break; + + case VAR_1: + printf(" VAR \n"); + break; + + case INTEGER_1: + printf(" INTEGER (KEYWORD) \n"); + break; + + case REAL_1: + printf(" REAL (KEYWORD) \n"); + break; + + case ARRAY_1: + printf(" ARRAY \n"); + break; + + case OF_1: + printf(" OF \n"); + break; + + case PROCEDURE_1: + printf(" PROCEDURE \n"); + break; + + case FORWARD_1: + printf(" FORWARD \n"); + break; + + case FUNCTION_1: + printf(" FUNCTION \n"); + break; + + case BEGIN_1: + printf(" BEGIN \n"); + break; + + case END_1: + printf(" END \n"); + break; + + case READ_1: + printf(" READ \n"); + break; + + case WRITE_1: + printf(" WRITE \n"); + break; + + case WRITELN_1: + printf(" WRITELN \n"); + break; + + case IF_1: + printf(" IF \n"); + break; + + case THEN_1: + printf(" THEN \n"); + break; + + case ELSE_1: + printf(" ELSE \n"); + break; + + case WHILE_1: + printf(" WHILE \n"); + break; + + case DO_1: + printf(" DO \n"); + break; + + case NOT_1: + printf(" NOT \n"); + break; + + case ID_1: + printf(" Identifier: "); + GETSTR(); + printf("%s\n",LEXEME); + break; + + case LEFT_PAREN_1: + printf(" LEFT PAREN '(' \n"); + break; + + case RIGHT_PAREN_1: + printf(" RIGHT PAREN ')' \n"); + break; + + case LEFT_BRACKET_1: + printf(" LEFT BRACKET ([) \n"); + break; + + case RIGHT_BRACKET_1: + printf(" RIGHT BRACKET (]) \n"); + break; + + case COMMA_1: + printf(" COMMA (,) \n"); + break; + + case SEMICOLON_1: + printf(" SEMICOLON (;) \n"); + break; + + default: + ERROR_CNT ++; + printf("------------>ERROR: A Valid TOKEN Code is not the\n"); + printf(" first item on the input line."); + printf(" <--------\n"); + GETSTR(); + } + GETCHR(); + if (CH != '\n' && EOF_FLAG) { + ERROR_CNT ++; + printf("------------>ERROR: Expected a Newline Character <--------\n"); + } + FLUSH(); + } + else EOF_FLAG = 0; + } /* end while (EOF_FLAG) */ + printf("EOF\n"); + if (ERROR_CNT) + printf("****** %d format errors found in output of your scanner.\n", + ERROR_CNT); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/scanner.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/scanner.h:1.1 *** /dev/null Tue Oct 5 14:30:54 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/scanner.h Tue Oct 5 14:30:43 2004 *************** *** 0 **** --- 1,57 ---- + + /* USEFUL MACRO DEFINITIONS */ + + #define ERRORMSG_1 0 + #define LINE_1 1 + #define ADDOP_1 2 + #define PLUS_1 '+' + #define MINUS_1 '-' + #define OR_1 260 + #define MULOP_1 3 + #define TIMES_1 '*' + #define SLASH_1 '/' + #define AND_1 259 + #define DIV_1 261 + #define RELOP_1 4 + #define EQUAL_1 '=' + #define NOTEQUAL_1 256 + #define LESSTHANOREQUAL_1 257 + #define LESSTHAN_1 '<' + #define GREATERTHANOREQUAL_1 258 + #define GREATERTHAN_1 '>' + #define ASSIGN_1 5 + #define COLON_1 6 + #define DOTDOT_1 7 + #define DOT_1 8 + #define INTEGER_NUMBER_1 9 + #define ILLEGAL_1 0 + #define VALID_1 1 + #define REAL_NUMBER_1 10 + #define PROGRAM_1 11 + #define VAR_1 12 + #define INTEGER_1 13 + #define REAL_1 14 + #define ARRAY_1 15 + #define OF_1 16 + #define FORWARD_1 17 + #define PROCEDURE_1 18 + #define FUNCTION_1 19 + #define BEGIN_1 20 + #define END_1 21 + #define READ_1 22 + #define WRITE_1 23 + #define WRITELN_1 24 + #define IF_1 25 + #define THEN_1 26 + #define ELSE_1 27 + #define WHILE_1 28 + #define DO_1 29 + #define NOT_1 30 + #define ID_1 31 + #define LEFT_PAREN_1 32 + #define RIGHT_PAREN_1 33 + #define LEFT_BRACKET_1 34 + #define RIGHT_BRACKET_1 35 + #define COMMA_1 36 + #define SEMICOLON_1 37 + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/stringI.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/stringI.c:1.1 *** /dev/null Tue Oct 5 14:30:54 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/fixoutput/stringI.c Tue Oct 5 14:30:43 2004 *************** *** 0 **** --- 1,79 ---- + /* To compile use: + cc stringI.c lex.o -lm + */ + + #include + #include + #include "scanner.h" /* Useful Macro Definitions */ + + #define LEX_LEN_INCR 256 + #define PERROR_1 0 + + char CH; /* Current input Character */ + char *LEXEME; /* Input String */ + + char *FRONT,*BACK; /* FRONT and BACK characters of Input String*/ + unsigned LEX_LEN = 0; /* Size of the Input String Buffer */ + + /* FORWORD function definitions */ + /* extern char *calloc(); */ + + void FLUSH(void) + /* Clear input string (LEXEME), reset buffer to correct size, and reset + pointers */ + { + /* reset buffer to correst size if necessary */ + if (LEX_LEN > LEX_LEN_INCR) + { + cfree(LEXEME); + LEX_LEN = LEX_LEN_INCR; + LEXEME = calloc(LEX_LEN,sizeof(CH)); + } + /* Clear input string */ + *LEXEME = 0; + /* reset pointers */ + BACK = LEXEME; + FRONT = BACK - 1; + } + + void GETCHR(void) + /* gets the next character form input file and expands buffer if needed */ + { + char *TEMP; + int I; + + /* expand buffer if needed */ + if (FRONT-BACK >= LEX_LEN-3) + { + LEX_LEN = LEX_LEN + LEX_LEN_INCR; + TEMP = calloc(LEX_LEN,sizeof(CH)); + for (I = 0; I < LEX_LEN - LEX_LEN_INCR; I ++) + TEMP[I] = LEXEME[I]; + } + + /* get next character */ + CH = getc(stdin); + /* update input string appropriately */ + FRONT ++; + *FRONT = CH; + *(FRONT+1) = 0; + } + + void BACKUP(void) + /* backups input string to last character of input and writes current + character back on input file */ + { + if (FRONT < BACK) + (void) printf( + "%D SCANNER ERROR: Tried to BACKUP past beginning of a Token\n", + PERROR_1); + else + { + /* put current char back on input file */ + (void) ungetc(CH,stdin); + /* backup input string one character */ + *FRONT = 0; + FRONT --; + CH = *FRONT; + } + } From lattner at cs.uiuc.edu Tue Oct 5 14:42:00 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 14:42:00 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/ Message-ID: <200410051942.OAA24971@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 14:42:27 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 14:42:27 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/Makefile count.c countlib.c endgame.c eval.c exambord.c findcolr.c findnext.c findopen.c findpatn.c findsavr.c findwinr.c fioe.c genmove.c getij.c getmove.c initmark.c main.c matchpat.c opening.c openregn.c random.c seed.c sethand.c showbord.c showinst.c suicide.c Message-ID: <200410051942.OAA25037@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo: Makefile added (r1.1) count.c added (r1.1) countlib.c added (r1.1) endgame.c added (r1.1) eval.c added (r1.1) exambord.c added (r1.1) findcolr.c added (r1.1) findnext.c added (r1.1) findopen.c added (r1.1) findpatn.c added (r1.1) findsavr.c added (r1.1) findwinr.c added (r1.1) fioe.c added (r1.1) genmove.c added (r1.1) getij.c added (r1.1) getmove.c added (r1.1) initmark.c added (r1.1) main.c added (r1.1) matchpat.c added (r1.1) opening.c added (r1.1) openregn.c added (r1.1) random.c added (r1.1) seed.c added (r1.1) sethand.c added (r1.1) showbord.c added (r1.1) showinst.c added (r1.1) suicide.c added (r1.1) --- Log message: New benchmark: gnu go 1.1. This also has no input, but should at least be easier to come up with one --- Diffs of the changes: (+2932 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/Makefile:1.1 *** /dev/null Tue Oct 5 14:42:26 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/Makefile Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,5 ---- + LEVEL = ../../../.. + + PROG = gnugo + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/count.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/count.c:1.1 *** /dev/null Tue Oct 5 14:42:26 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/count.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,97 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + + extern unsigned char p[19][19], ml[19][19]; + extern int lib; + + void count(int i, int j, int color) + /* count liberty of color piece at i, j */ + { + /* set current piece as marked */ + ml[i][j] = EMPTY; + + /* check North neighbor */ + if (i != EMPTY) + { + if ((p[i - 1][j] == EMPTY) && ml[i - 1][j]) + { + ++lib; + ml[i - 1][j] = EMPTY; + } + else + if ((p[i - 1][j] == color) && ml[i - 1][j]) + count(i - 1, j, color); + } + /* check South neighbor */ + if (i != 18) + { + if ((p[i + 1][j] == EMPTY) && ml[i + 1][j]) + { + ++lib; + ml[i + 1][j] = EMPTY; + } + else + if ((p[i + 1][j] == color) && ml[i + 1][j]) + count(i + 1, j, color); + } + /* check West neighbor */ + if (j != EMPTY) + { + if ((p[i][j - 1] == EMPTY) && ml[i][j - 1]) + { + ++lib; + ml[i][j - 1] = EMPTY; + } + else + if ((p[i][j - 1] == color) && ml[i][j - 1]) + count(i, j - 1, color); + } + /* check East neighbor */ + if (j != 18) + { + if ((p[i][j + 1] == EMPTY) && ml[i][j + 1]) + { + ++lib; + ml[i][j + 1] = EMPTY; + } + else + if ((p[i][j + 1] == color) && ml[i][j + 1]) + count(i, j + 1, color); + } + } /* end count */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/countlib.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/countlib.c:1.1 *** /dev/null Tue Oct 5 14:42:26 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/countlib.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,55 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + extern unsigned char ml[19][19]; + + extern void count(int i, int j, int color); + + void countlib(int m, int n, int color) + /* count liberty of color piece at m, n */ + { + int i, j; + + /* set all piece as unmarked */ + for (i = 0; i < 19; i++) + for (j = 0; j < 19; j++) + ml[i][j] = 1; + + /* count liberty of current piece */ + count(m, n, color); + } /* end countlib */ + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/endgame.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/endgame.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/endgame.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,135 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + + extern unsigned char p[19][19]; + extern int mymove, umove; + extern int mk, uk; /* piece captured */ + + extern int getij(char move[], int *i, int *j); + extern void showboard(void); + extern int findcolor(int i, int j); + + void endgame(void) + /* count pieces and announce the winner */ + { + char an[10]; + int i, j, mtot, utot, cont; + + printf("\nTo count score, we need the following steps:\n"); + printf("First, I need you to remove all dead pieces on the board.\n"); + printf("Second, I need you to fill in neutral territories with "); + printf("pieces.\n"); + printf("Last, I will fill in all pieces and anounce the winner.\n"); + + /* remove dead pieces */ + printf("\nFirst, you should enter the dead pieces (blank and white) to"); + printf(" be removed. Enter\n"); + printf(" 'stop' when you have finished.\n"); + + cont = 1; + do { + printf("Dead piece? "); + scanf("%s", an); + if (strcmp(an, "stop")) + { + getij(an, &i, &j); + if (p[i][j] == mymove) + { + p[i][j] = EMPTY; + mk++; + } + else + if (p[i][j] == umove) + { + p[i][j] = EMPTY; + uk++; + } + showboard(); + } + else + cont = 0; + } + while (cont); + + /* fill in neutral */ + printf("Next, you need to fill in pieces (black and white) in all neutral"); + printf(" territories.\n"); + printf("Enter your and my pieces alternately and enter 'stop' when finish\n"); + cont = 1; + + do { + printf("Your piece? "); + scanf("%s", an); + if (strcmp(an, "stop")) + { + getij(an, &i, &j); + p[i][j] = umove; + printf("My piece? "); + scanf("%s", an); + getij(an, &i, &j); + p[i][j] = mymove; + showboard(); + } + else + cont = 0; + } + while (cont); + + /* set empty to side they belong to */ + for (i = 0; i < 19; i++) + for (j = 0; j < 19; j++) + if (p[i][j] == EMPTY) + p[i][j] = findcolor(i, j); + + /* count total */ + mtot = 0; utot = 0; + for (i = 0; i < 19; i++) + for (j = 0; j < 19; j++) + if (p[i][j] == mymove) + ++mtot; + else + if (p[i][j] == umove) + ++utot; + + showboard(); + printf("Your total number of pieces %d\n", utot); + printf("My total number of pieces %d\n", mtot); + + } /* end endgame */ + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/eval.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/eval.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/eval.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,57 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + extern unsigned char p[19][19], l[19][19]; + extern int lib; + + extern void countlib(int m, int n, int color); + + void eval(int color) + /* evaluate liberty of color pieces */ + { + int i, j; + + /* find liberty of each piece */ + for (i = 0; i < 19; i++) + for (j = 0; j < 19; j++) + if (p[i][j] == color) + { + lib = 0; + countlib(i, j, color); + l[i][j] = lib; + } + } /* end eval */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/exambord.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/exambord.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/exambord.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,101 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + + extern unsigned char p[19][19], l[19][19]; + extern int mymove; + extern int mik, mjk, uik, ujk, mk, uk; /* piece captured */ + + extern void eval(int color); + + void examboard(int color) + /* examine pieces */ + { + int i, j, n; + + + /* find liberty of each piece */ + eval(color); + + /* initialize piece captured */ + if (color == mymove) + { + mik = -1; + mjk = -1; + } + else + { + uik = -1; + ujk = -1; + } + n = 0; /* The number of captures this move for Ko purposes */ + + /* remove all piece of zero liberty */ + for (i = 0; i < 19; i++) + for (j = 0; j < 19; j++) + if ((p[i][j] == color) && (l[i][j] == 0)) + { + p[i][j] = EMPTY; + /* record piece captured */ + if (color == mymove) + { + mik = i; + mjk = j; + ++mk; + } + else + { + uik = i; + ujk = j; + ++uk; + } + ++n; /* increment number of captures on this move */ + } + /* reset to -1 if more than one stone captured since no Ko possible */ + if (color == mymove && n > 1) + { + mik = -1; + mjk = -1; + } + else if ( n > 1 ) + { + uik = -1; + ujk = -1; + } + } /* end examboard */ + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findcolr.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findcolr.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findcolr.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,101 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + + extern unsigned char p[19][19]; + + int findcolor(int i, int j) + /* find color for empty piece */ + { + int k, color1, color2; + + /* check North neighbor */ + color1 = 0; + k = i; + do --k; + while ((p[k][j] == EMPTY) && (k > 0)); + color1 = p[k][j]; + + /* check South neighbor */ + color2 = 0; + k = i; + do k++; + while ((p[k][j] == EMPTY) && (k < 18)); + color2 = p[k][j]; + + if (color1) + { + if ((color1 == color2) || (color2 == 0)) + return color1; + else + return 0; /* cannot determine */ + } + else + if (color2) + return color2; + else /* both zero */ + { + /* check West neighbor */ + color1 = 0; + k = j; + do --k; + while ((p[i][k] == EMPTY) && (k > 0)); + color1 = p[i][k]; + + /* check East neighbor */ + color2 = 0; + k = j; + do k++; + while ((p[i][k] == EMPTY) && (k < 18)); + color2 = p[i][k]; + + if (color1) + { + if ((color1 == color2) || (color2 == 0)) + return color1; + else + return 0; /* cannot determine */ + } + else + if (color2) + return color2; + else + return 0; + } + } /* end findcolor */ + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findnext.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findnext.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findnext.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,189 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + + extern unsigned char p[19][19], ma[19][19]; + extern int mymove; + extern int lib; + + extern void countlib(int m, int n, int color); + extern int fval(int newlib, int minlib); + + int findnextmove(int m, int n, int *i, int *j, int *val, int minlib) + /* find new move i, j from group containing m, n */ + { + int ti, tj, tval; + int found = 0; + + *i = -1; *j = -1; *val = -1; + /* mark current position */ + ma[m][n] = 1; + + /* check North neighbor */ + if (m != 0) + if (p[m - 1][n] == EMPTY) + { + ti = m - 1; + tj = n; + lib = 0; + countlib(ti, tj, mymove); + tval = fval(lib, minlib); + found = 1; + } + else + if ((p[m - 1][n] == mymove) && !ma[m - 1][n]) + if (findnextmove(m - 1, n, &ti, &tj, &tval, minlib)) + found = 1; + + if (found) + { + found = 0; + if (tval > *val) + { + *val = tval; + *i = ti; + *j = tj; + } + if (minlib == 1) return 1; + } + + /* check South neighbor */ + if (m != 18) + if (p[m + 1][n] == EMPTY) + { + ti = m + 1; + tj = n; + lib = 0; + countlib(ti, tj, mymove); + tval = fval(lib, minlib); + found = 1; + } + else + if ((p[m + 1][n] == mymove) && !ma[m + 1][n]) + if (findnextmove(m + 1, n, &ti, &tj, &tval, minlib)) + found = 1; + + if (found) + { + found = 0; + if (tval > *val) + { + *val = tval; + *i = ti; + *j = tj; + } + if (minlib == 1) return 1; + } + + /* check West neighbor */ + if (n != 0) + if (p[m][n - 1] == EMPTY) + { + ti = m; + tj = n - 1; + lib = 0; + countlib(ti, tj, mymove); + tval = fval(lib, minlib); + found = 1; + } + else + if ((p[m][n - 1] == mymove) && !ma[m][n - 1]) + if (findnextmove(m, n - 1, &ti, &tj, &tval, minlib)) + found = 1; + + if (found) + { + found = 0; + if (tval > *val) + { + *val = tval; + *i = ti; + *j = tj; + } + if (minlib == 1) return 1; + } + + /* check East neighbor */ + if (n != 18) + if (p[m][n + 1] == EMPTY) + { + ti = m; + tj = n + 1; + lib = 0; + countlib(ti, tj, mymove); + tval = fval(lib, minlib); + found = 1; + } + else + if ((p[m][n + 1] == mymove) && !ma[m][n + 1]) + if (findnextmove(m, n + 1, &ti, &tj, &tval, minlib)) + found = 1; + + if (found) + { + found = 0; + if (tval > *val) + { + *val = tval; + *i = ti; + *j = tj; + } + if (minlib == 1) return 1; + } + + if (*val > 0) /* found next move */ + return 1; + else /* next move failed */ + return 0; + } /* end findnextmove */ + + + int fval(int newlib, int minlib) + /* evaluate new move */ + { + int k, val; + + if (newlib <= minlib) + val = -1; + else + { + k = newlib - minlib; + val = 40 + (k - 1) * 50 / (minlib * minlib * minlib); + } + return val; + } /* end fval */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findopen.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findopen.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findopen.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,115 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + + extern unsigned char p[19][19], ma[19][19]; + extern int mik, mjk; /* piece captured */ + + int findopen(int m, int n, int i[], int j[], int color, int minlib, int *ct) + /* find all open spaces i, j from m, n */ + { + /* mark this one */ + ma[m][n] = 1; + + /* check North neighbor */ + if (m != 0) + { + if ((p[m - 1][n] == EMPTY) && (((m - 1) != mik) || (n != mjk))) + { + i[*ct] = m - 1; + j[*ct] = n; + ++*ct; + if (*ct == minlib) return 1; + } + else + if ((p[m - 1][n] == color) && !ma[m - 1][n]) + if (findopen(m - 1, n, i, j, color, minlib, ct) && (*ct == minlib)) + return 1; + } + + /* check South neighbor */ + if (m != 18) + { + if ((p[m + 1][n] == EMPTY) && (((m + 1) != mik) || (n != mjk))) + { + i[*ct] = m + 1; + j[*ct] = n; + ++*ct; + if (*ct == minlib) return 1; + } + else + if ((p[m + 1][n] == color) && !ma[m + 1][n]) + if (findopen(m + 1, n, i, j, color, minlib, ct) && (*ct == minlib)) + return 1; + } + + /* check West neighbor */ + if (n != 0) + { + if ((p[m][n - 1] == EMPTY) && ((m != mik) || ((n - 1) != mjk))) + { + i[*ct] = m; + j[*ct] = n - 1; + ++*ct; + if (*ct == minlib) return 1; + } + else + if ((p[m][n - 1] == color) && !ma[m][n - 1]) + if (findopen(m, n - 1, i, j, color, minlib, ct) && (*ct == minlib)) + return 1; + } + + /* check East neighbor */ + if (n != 18) + { + if ((p[m][n + 1] == EMPTY) && ((m != mik) || ((n + 1) != mjk))) + { + i[*ct] = m; + j[*ct] = n + 1; + ++*ct; + if (*ct == minlib) return 1; + } + else + if ((p[m][n + 1] == color) && !ma[m][n + 1]) + if (findopen(m, n + 1, i, j, color, minlib, ct) && (*ct == minlib)) + return 1; + } + + /* fail to find open space */ + return 0; + } /* end findopen */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findpatn.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findpatn.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findpatn.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,193 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + + extern unsigned char p[19][19]; + extern int mymove, umove; + extern int opn[9]; + + extern int opening(int *i, int *j, int *cnd, int type); + extern int openregion(int i1, int j1, int i2, int j2); + extern int matchpat(int m, int n, int *i, int *j, int *val); + + int findpatn(int *i, int *j, int *val) + /* find pattern to match for next move */ + { + int m, n; + int ti, tj, tval; + static int cnd, mtype; /* game tree node number, move type */ + /* mtype = 0, basic; 1, inverted; 2, reflected; 3, inverted & reflected */ + + /* open game then occupy corners */ + if (opn[4]) /* continue last move */ + { + opn[4] = 0; /* clear flag */ + if (opening(i, j, &cnd, mtype)) opn[4] = 1; /* more move then reset flag */ + if (p[*i][*j] == EMPTY) /* valid move */ + { + *val = 80; + return 1; + } + else + opn[4] = 0; + } + + if (opn[0]) /* Northwest corner */ + { + opn[0] = 0; /* clear flag */ + if (openregion(0, 0, 5, 5)) + { + cnd = 0; + mtype = 0; + opening(i, j, &cnd, mtype); /* get new node for next move */ + if (opening(i, j, &cnd, mtype)) opn[4] = 1; + *val = 80; + return 1; + } + } + + if (opn[1]) /* Southwest corner */ + { + opn[1] = 0; + if (openregion(13, 0, 18, 5)) + { + cnd = 0; + mtype = 1; + opening(i, j, &cnd, mtype); /* get new node for next move */ + if (opening(i, j, &cnd, mtype)) opn[4] = 1; + *val = 80; + return 1; + } + } + + if (opn[2]) /* Northeast corner */ + { + opn[2] = 0; + if (openregion(0, 13, 5, 18)) + { + cnd = 0; + mtype = 2; + opening(i, j, &cnd, mtype); /* get new node for next move */ + if (opening(i, j, &cnd, mtype)) opn[4] = 1; + *val = 80; + return 1; + } + } + + if (opn[3]) /* Northeast corner */ + { + opn[3] = 0; + if (openregion(13, 13, 18, 18)) + { + cnd = 0; + mtype = 3; + opening(i, j, &cnd, mtype); /* get new node for next move */ + if (opening(i, j, &cnd, mtype)) opn[4] = 1; + *val = 80; + return 1; + } + } + + /* occupy edges */ + if (opn[5]) /* North edge */ + { + opn[5] = 0; + if (openregion(0, 6, 4, 11)) + { + *i = 3; + *j = 9; + *val = 80; + return 1; + } + } + + if (opn[6]) /* South edge */ + { + opn[6] = 0; + if (openregion(18, 6, 14, 11)) + { + *i = 15; + *j = 9; + *val = 80; + return 1; + } + } + + if (opn[7]) /* West edge */ + { + opn[7] = 0; + if (openregion(6, 0, 11, 4)) + { + *i = 9; + *j = 3; + *val = 80; + return 1; + } + } + + if (opn[8]) /* East edge */ + { + opn[8] = 0; + if (openregion(6, 18, 11, 14)) + { + *i = 9; + *j = 15; + *val = 80; + return 1; + } + } + + *i = -1; + *j = -1; + *val = -1; + + /* find local pattern */ + for (m = 0; m < 19; m++) + for (n = 0; n < 19; n++) + if ((p[m][n] == mymove) && + (matchpat(m, n, &ti, &tj, &tval) && (tval > *val))) + { + *val = tval; + *i = ti; + *j = tj; + } + if (*val > 0) /* pattern found */ + return 1; + else /* no match found */ + return 0; + } /* end findpatn */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findsavr.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findsavr.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findsavr.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,75 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + + + + */ + + #include + + extern unsigned char p[19][19], l[19][19]; + extern int mymove; + + extern void initmark(void); + extern int findnextmove(int m, int n, int *i, int *j, int *val, int minlib); + + int findsaver(int *i, int *j, int *val) + /* find move if any pieces is threaten */ + { + int m, n, minlib; + int ti, tj, tval; + + *i = -1; *j = -1; *val = -1; + for (minlib = 1; minlib < 4; minlib++) + { + /* count piece with minimum liberty */ + for (m = 0; m < 19; m++) + for (n = 0; n < 19; n++) + if ((p[m][n] == mymove) && (l[m][n] == minlib)) + /* find move to save pieces */ + { + initmark(); + if (findnextmove(m, n, &ti, &tj, &tval, minlib) && (tval > *val)) + { + *val = tval; + *i = ti; + *j = tj; + } + } + } + if (*val > 0) /* find move */ + return 1; + else /* move not found */ + return 0; + } /* findsaver */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findwinr.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findwinr.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/findwinr.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,106 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + + extern unsigned char p[19][19], l[19][19]; + extern int mymove, umove; + extern int lib; + + extern void initmark(void); + extern int findopen(int m, int n, int i[], int j[], int color, int minlib, int *ct); + extern void countlib(int m, int n, int color); + + int findwinner(int *i, int *j, int *val) + /* find opponent piece to capture or attack */ + { + int m, n, ti[3], tj[3], tval, ct, u, v, lib1; + + *i = -1; *j = -1; *val = -1; + + /* find opponent with liberty less than four */ + for (m = 0; m < 19; m++) + for (n = 0; n < 19; n++) + if ((p[m][n] == umove) && (l[m][n] < 4)) + { + ct = 0; + initmark(); + if (findopen(m, n, ti, tj, umove, l[m][n], &ct)) + { + if (l[m][n] == 1) + { + if (*val < 120) + { + *val = 120; + *i = ti[0]; + *j = tj[0]; + } + } + else + for (u = 0; u < l[m][n]; u++) + for (v = 0; v < l[m][n]; v++) + if (u != v) + { + lib = 0; + countlib(ti[u], tj[u], mymove); + if (lib > 0) /* valid move */ + { + lib1 = lib; + p[ti[u]][tj[u]] = mymove; + /* look ahead opponent move */ + lib = 0; + countlib(ti[v], tj[v], umove); + if ((lib1 == 1) && (lib > 0)) + tval = 0; + else + tval = 120 - 20 * lib; + if (*val < tval) + { + *val = tval; + *i = ti[u]; + *j = tj[u]; + } + p[ti[u]][tj[u]] = EMPTY; + } + } + } + } + if (*val > 0) /* find move */ + return 1; + else /* fail to find winner */ + return 0; + } /* end findwinner */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/fioe.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/fioe.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/fioe.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,84 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + extern unsigned char p[19][19]; + extern int mymove; + + int fioe(int i, int j) + { + /* check top edge */ + if (i == 0) + { + if ((j == 0) && ((p[1][0] == mymove) && (p[0][1] == mymove))) return 1; + if ((j == 18) && ((p[1][18] == mymove) && (p[0][17] == mymove))) return 1; + if ((p[1][j] == mymove) && + ((p[0][j - 1] == mymove) && (p[0][j + 1] == mymove))) return 1; + else + return 0; + } + /* check bottom edge */ + if (i == 18) + { + if ((j == 0) && ((p[17][0] == mymove) && (p[18][1] == mymove))) return 1; + if ((j == 18) && ((p[17][18] == mymove) && (p[18][17] == mymove))) return 1; + if ((p[17][j] == mymove) && + ((p[18][j - 1] == mymove) && (p[18][j + 1] == mymove))) + return 1; + else + return 0; + } + /* check left edge */ + if (j == 0) + if ((p[i][1] == mymove) && + ((p[i - 1] [0] == mymove) && (p[i + 1][0] == mymove))) + return 1; + else + return 0; + /* check right edge */ + if (j == 18) + if ((p[i][17] == mymove) && + ((p[i - 1] [18] == mymove) && (p[i + 1][18] == mymove))) + return 1; + else + return 0; + /* check center pieces */ + if (((p[i][j - 1] == mymove) && (p[i][j + 1] == mymove)) && + ((p[i - 1][j] == mymove) && (p[i + 1][j] == mymove))) + return 1; + else + return 0; + } /* fioe */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/genmove.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/genmove.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/genmove.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,151 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + #define MAXTRY 400 + + extern unsigned char p[19][19]; + extern int mymove, umove; + extern int rd, lib, pass; + + extern void eval(int color); + extern int findwinner(int *i, int *j, int *val); + extern int findsaver(int *i, int *j, int *val); + extern int findpatn(int *i, int *j, int *val); + extern void random_nasko(int *i); + extern void countlib(int m, int n, int color); + extern int fioe(int i, int j); + + void genmove(int *i, int *j) + /* generate computer move */ + { + int ti, tj, tval; + char a; + int ii, val; + int try1 = 0; /* number of try */ + + /* initialize move and value */ + *i = -1; *j = -1; val = -1; + + /* re-evaluate liberty of opponent pieces */ + eval(umove); + + /* find opponent piece to capture or attack */ + if (findwinner(&ti, &tj, &tval)) + if (tval > val) + { + val = tval; + *i = ti; + *j = tj; + } + + /* save any piece if threaten */ + if (findsaver(&ti, &tj, &tval)) + if (tval > val) + { + val = tval; + *i = ti; + *j = tj; + } + + /* try match local play pattern for new move */ + if (findpatn(&ti, &tj, &tval)) + if (tval > val) + { + val = tval; + *i = ti; + *j = tj; + } + + /* no urgent move then do random move */ + if (val < 0) + do { + random_nasko(&rd); + *i = rd % 19; + /* avoid low line and center region */ + if ((*i < 2) || (*i > 16) || ((*i > 5) && (*i < 13))) + { + random_nasko(&rd); + *i = rd % 19; + if ((*i < 2) || (*i > 16)) + { + random_nasko(&rd); + *i = rd % 19; + } + } + random_nasko(&rd); + *j = rd % 19; + /* avoid low line and center region */ + if ((*j < 2) || (*j > 16) || ((*j > 5) && (*j < 13))) + { + random_nasko(&rd); + *j = rd % 19; + if ((*j < 2) || (*j > 16)) + { + random_nasko(&rd); + *j = rd % 19; + } + } + lib = 0; + countlib(*i, *j, mymove); + } + /* avoid illegal move, liberty one or suicide, fill in own eye */ + while ((++try1 < MAXTRY) + && ((p[*i][*j] != EMPTY) || (lib < 2) || fioe(*i, *j))); + + if (try1 >= MAXTRY) /* computer pass */ + { + pass++; + printf("I pass.\n"); + *i = -1; + } + else /* find valid move */ + { + pass = 0; + printf("my move: "); + if (*j < 8) + a = *j + 65; + else + a = *j + 66; + printf("%c", a); + ii = 19 - *i; + if (ii < 10) + printf("%1d\n", ii); + else + printf("%2d\n", ii); + } + } /* end genmove */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/getij.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/getij.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/getij.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,63 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + int getij(char move[], int *i, int *j) + /* convert string input to i, j coordinate */ + { + int k; + + if ((move[0] >= 65) && (move[0] <= 72)) + *j = move[0] - 65; + else + if ((move[0] >= 74) && (move[0] <= 84)) + *j = move[0] - 66; + else + if ((move[0] >= 97) && (move[0] <= 104)) + *j = move[0] - 97; + else + if ((move[0] >= 106) && (move[0] <= 116)) + *j = move[0] - 98; + else + return 0; + k = move[1] - 48; + if (move[2]) k = k * 10 + move[2] - 48; + *i = 19 - k; + if ((*i >= 0) && (*i <= 18)) + return 1; + else + return 0; + } /* end getij */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/getmove.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/getmove.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/getmove.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,101 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + + extern unsigned char p[19][19]; + extern int mymove, umove; + extern int play, pass; + extern int mk, uk; /* piece captured */ + extern int opn[9]; + + extern int getij(char move[], int *i, int *j); + extern int suicide(int i, int j); + + void getmove(char move[], int *i, int *j) + /* interpret response of human move to board position */ + { + FILE *fp; + int m, n; + + if (strcmp(move, "stop") == 0) + /* stop game */ + play = 0; + else + { + if (strcmp(move, "save") == 0) + /* save data and stop game */ + { + fp = fopen("gnugo.dat", "w"); + /* save board configuration */ + for (m = 0; m < 19; m++) + for (n = 0; n < 19; n++) + fprintf(fp, "%c", p[m][n]); + /* my color, pieces captured */ + fprintf(fp, "%d %d %d ", mymove, mk, uk); + /* opening pattern flags */ + for (m = 0; m < 9; m++) + fprintf(fp, "%d ", opn[m]); + + fclose(fp); + play = -1; + } + else + { + if (strcmp(move, "pass") == 0) + /* human pass */ + { + pass++; + *i = -1; /* signal pass */ + } + else + { + pass = 0; + /* move[0] from A to T, move[1] move[2] from 1 to 19 */ + /* convert move to coordinate */ + if (!getij(move, i, j) || (p[*i][*j] != EMPTY) || suicide(*i, *j)) + { + if (feof(stdin)) exit(1); + printf("illegal move !\n"); + printf("your move? "); + scanf("%s", move); + getmove(move, i, j); + } + } + } + } + } /* end getmove */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/initmark.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/initmark.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/initmark.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,47 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + extern unsigned char ma[19][19]; + + void initmark(void) + /* initialize all marking with zero */ + { + int i, j; + + for (i = 0; i < 19; i++) + for (j = 0; j < 19; j++) + ma[i][j] = 0; + } /* end initmark */ + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/main.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/main.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/main.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,183 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + #include + + #define EMPTY 0 + + extern void showinst(void); + extern void seed(int *i); + extern void sethand(int i); + extern void showboard(void); + extern void genmove(int *i, int *j); + extern void getmove(char move[], int *i, int *j); + extern void examboard(int color); + extern void endgame(void); + + unsigned char p[19][19], l[19][19], ma[19][19], ml[19][19]; + int mymove, umove; + int rd, lib, play, pass; + int mik, mjk, uik, ujk, mk, uk; /* piece captured */ + int opn[9]; /* opening pattern flag */ + + int main(void) + { + FILE *fp; + int i, j; + char move[10], ans[5]; + int cont = 0; + + /* show instruction */ + showinst(); + + if ((fp = fopen("gnugo.dat", "r")) != NULL) /* continue old game */ + { + cont = 1; + + /* read board configuration */ + for (i = 0; i < 19; i++) + for (j = 0; j < 19; j++) + fscanf(fp, "%c", &p[i][j]); + + /* read my color, pieces captured */ + fscanf(fp, "%d %d %d ", &mymove, &mk, &uk); + /* read opening pattern flags */ + for (i = 0; i < 9; i++) + fscanf(fp, "%d ", &opn[i]); + + fclose(fp); + umove = 3 - mymove; + + /* delete file */ + unlink("gnugo.dat"); + } + else + { + /* init opening pattern numbers to search */ + for (i = 0; i < 9; i++) + opn[i] = 1; + opn[4] = 0; + + /* init board */ + for (i = 0; i < 19; i++) + for (j = 0; j < 19; j++) + p[i][j] = EMPTY; + /* init global variables */ + mk = 0; uk = 0; + } + + /* init global variables */ + play = 1; + pass = 0; + mik = -1; mjk = -1; + uik = -1; ujk = -1; + seed(&rd); /* start random number seed */ + + if (!cont) /* new game */ + { + /* ask for handicap */ + printf("Number of handicap for black (0 to 17)? "); + scanf("%d", &i); + getchar(); + sethand(i); + + /* display game board */ + showboard(); + + /* choose color */ + printf("\nChoose side(b or w)? "); + scanf("%c",ans); + if (ans[0] == 'b') + { + mymove = 1; /* computer white */ + umove = 2; /* human black */ + if (i) + { + genmove(&i, &j); /* computer move */ + p[i][j] = mymove; + } + } + else + { + mymove = 2; /* computer black */ + umove = 1; /* human white */ + if (i == 0) + { + genmove(&i, &j); /* computer move */ + p[i][j] = mymove; + } + } + } + + showboard(); + + /* main loop */ + while (play > 0) + { + printf("your move? "); + scanf("%s", move); + getmove(move, &i, &j); /* read human move */ + if (play > 0) + { + if (i >= 0) /* not pass */ + { + p[i][j] = umove; + examboard(mymove); /* remove my dead pieces */ + } + if (pass != 2) + { + genmove(&i, &j); /* computer move */ + if (i >= 0) /* not pass */ + { + p[i][j] = mymove; + examboard(umove); /* remove your dead pieces */ + } + } + showboard(); + } + if (pass == 2) play = 0; /* both pass then stop game */ + } + + if (play == 0) + { + /* finish game and count pieces */ + getchar(); + printf("Do you want to count score (y or n)? "); + scanf("%c",ans); + if (ans[0] == 'y') endgame(); + } + return 0; + } /* end main */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/matchpat.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/matchpat.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/matchpat.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,204 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + #define MAXPC 16 + #define abs(x) ((x) < 0 ? -(x) : (x)) + #define line(x) (abs(x - 9)) + + extern unsigned char p[19][19]; + extern int mymove, umove; + extern int lib; + + extern void countlib(int m, int n, int color); + + int matchpat(int m, int n, int *i, int *j, int *val) + /* match pattern and get next move */ + { + struct patval {int x, y, att;}; /* pattern x, y coor and attribute */ + /* att = 0 - empty, 1 - your piece, 2 - my piece, 3 - my next move */ + /* 4 - empty on edge, 5 - your piece on edge, 6 - my piece on edge */ + struct pattern { + struct patval patn[MAXPC]; /* pattern */ + /* number of pieces in pattern, no. of transformation, pattern value */ + int patlen, trfno, patwt; + }; + + /* XXZ */ + /* #include "patterns.c" */ + #define EMPTY 0 + #define PATNO 24 + + static struct pattern pat[PATNO]; + /* XXZ */ + + /* transformation matrice */ + static int trf [8][2][2] = { + {{1, 0}, {0, 1}}, /* linear transfomation matrix */ + {{1, 0}, {0, -1}}, /* invert */ + {{0, 1}, {-1, 0}}, /* rotate 90 */ + {{0, -1}, {-1, 0}}, /* rotate 90 and invert */ + {{-1, 0}, {0, 1}}, /* flip left */ + {{-1, 0}, {0, -1}}, /* flip left and invert */ + {{0, 1}, {1, 0}}, /* rotate 90 and flip left */ + {{0, -1}, {1, 0}} /* rotate 90, flip left and invert */ + }; + int k, my, nx, l, r, cont; + int ti, tj, tval; + + *i = -1; *j = -1; *val = -1; + for (r = 0; r < PATNO; r++) + /* try each pattern */ + for (l = 0; l < pat[r].trfno; l++) + /* try each orientation transformation */ + { + k = 0; cont = 1; + while ((k != pat[r].patlen) && cont) + /* match each point */ + { + /* transform pattern real coordinate */ + nx = n + trf[l][0][0] * pat[r].patn[k].x + + trf[l][0][1] * pat[r].patn[k].y; + my = m + trf[l][1][0] * pat[r].patn[k].x + + trf[l][1][1] * pat[r].patn[k].y; + + /* outside the board */ + if ((my < 0) || ( my > 18) || (nx < 0) || (nx > 18)) + { + cont = 0; + break; + } + switch (pat[r].patn[k].att) { + case 0 : if (p[my][nx] == EMPTY) /* open */ + break; + else + { + cont = 0; + break; + } + case 1 : if (p[my][nx] == umove) /* your piece */ + break; + else + { + cont = 0; + break; + } + case 2 : if (p[my][nx] == mymove) /* my piece */ + break; + else + { + cont = 0; + break; + } + case 3 : if (p[my][nx] == EMPTY) /* open for new move */ + { + lib = 0; + countlib(my, nx, mymove); /* check liberty */ + if (lib > 1) /* move o.k. */ + { + ti = my; + tj = nx; + break; + } + else + { + cont = 0; + break; + } + } + else + { + cont = 0; + break; + } + case 4 : if ((p[my][nx] == EMPTY) /* open on edge */ + && ((my == 0) || (my == 18) || (nx == 0) || (nx == 18))) + break; + else + { + cont = 0; + break; + } + case 5 : if ((p[my][nx] == umove) /* your piece on edge */ + && ((my == 0) || (my == 18) || (nx == 0) || (nx == 18))) + break; + else + { + cont = 0; + break; + } + case 6 : if ((p[my][nx] == mymove) /* my piece on edge */ + && ((my == 0) || (my == 18) || (nx == 0) || (nx == 18))) + break; + else + { + cont = 0; + break; + } + } + ++k; + } + if (cont) /* match pattern */ + { + tval = pat[r].patwt; + if ((r >= 8) && (r <= 13)) /* patterns for expand region */ + { + if (line(ti) > 7) /* penalty on line 1, 2 */ + tval--; + else + if ((line(ti) == 6) || (line(ti) == 7)) + tval++; /* reward on line 3, 4 */ + + if (line(tj) > 7) /* penalty on line 1, 2 */ + tval--; + else + if ((line(tj) == 6) || (line(tj) == 7)) + tval++; /* reward on line 3, 4 */ + } + if (tval > *val) + { + *val = tval; + *i = ti; + *j = tj; + } + } + } + if (*val > 0) /* pattern matched */ + return 1; + else /* match failed */ + return 0; + } /* end matchpat */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/opening.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/opening.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/opening.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,92 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + extern int rd; + extern void random_nasko(int *i); + + int opening(int *i, int *j, int *cnd, int type) + /* get move for opening from game tree */ + { + struct tnode { + int i, j, ndct, next[8]; + }; + + static struct tnode tree[] = { + {-1, -1, 8, { 1, 2, 3, 4, 5, 6, 7, 20}}, /* 0 */ + {2, 3, 2, { 8, 9}}, + {2, 4, 1, {10}}, + {3, 2, 2, {11, 12}}, + {3, 3, 6, {14, 15, 16, 17, 18, 19}}, + {3, 4, 1, {10}}, /* 5 */ + {4, 2, 1, {13}}, + {4, 3, 1, {13}}, + {4, 2, 0}, + {4, 3, 0}, + {3, 2, 0}, /* 10 */ + {2, 4, 0}, + {3, 4, 0}, + {2, 3, 0}, + {2, 5, 1, {10}}, + {2, 6, 1, {10}}, /* 15 */ + {3, 5, 1, {10}}, + {5, 2, 1, {13}}, + {5, 3, 1, {13}}, + {6, 2, 1, {13}}, + {2, 2, 0} /* 20 */ + }; + int m; + + /* get i, j */ + if ((type == 1) || (type == 3)) + *i = 18 - tree[*cnd].i; /* inverted */ + else + *i = tree[*cnd].i; + if ((type == 2) || (type == 3)) + *j = 18 - tree[*cnd].j; /* reflected */ + else + *j = tree[*cnd].j; + if (tree[*cnd].ndct) /* more move */ + { + random_nasko(&rd); + m = rd % tree[*cnd].ndct; /* select move */ + *cnd = tree[*cnd].next[m]; /* new current node */ + return 1; + } + else + return 0; + } /* end opening */ + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/openregn.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/openregn.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/openregn.c Tue Oct 5 14:42:15 2004 *************** *** 0 **** --- 1,77 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + + extern unsigned char p[19][19]; + + int openregion(int i1, int j1, int i2, int j2) + /* check if region from i1, j1 to i2, j2 is open */ + { + int minx, maxx, miny, maxy, x, y; + + /* exchange upper and lower limits */ + + if (i1 < i2) + { + miny = i1; + maxy = i2; + } + else + { + miny = i2; + maxy = i1; + } + + if (j1 < j2) + { + minx = j1; + maxx = j2; + } + else + { + minx = j2; + maxx = j1; + } + + /* check for empty region */ + for (y = miny; y <= maxy; y++) + for (x = minx; x <= maxx; x++) + if (p[y][x] != EMPTY) return 0; + return 1; + } /* end openregion */ + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/random.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/random.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/random.c Tue Oct 5 14:42:16 2004 *************** *** 0 **** --- 1,49 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + extern void seed(int *i); + + void random_nasko(int *i) + /* random number generator */ + { + if (*i == 0) + seed(i); + else + { + *i = *i * 137 % 3833; + if (*i < 0) *i = -*i; + } + } /* end random */ + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/seed.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/seed.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/seed.c Tue Oct 5 14:42:16 2004 *************** *** 0 **** --- 1,79 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + /* + #define IBM 8086 + */ + + #define SUN 68000 + + #include + + #ifdef SUN + + #include + + #endif + + #ifdef IBM + + void seed(int *i) + /* start seed of random number generator for PC */ + /* Computer Innovation C86 compiler version */ + { + struct regval {int ax, bx, cx, dx, si, di, ds, es;}; + struct regval sreg, rreg; + + sreg.ax = 0x2c00; + sysint21(&sreg, &rreg); + *i = rreg.dx; + } /* end seed */ + #endif + + + #ifdef SUN + + void seed(int *i) + /* start seed of random number generator for Sun */ + { + struct timeval tp; + struct timezone tzp; + + gettimeofday(&tp, &tzp); + *i = tp.tv_usec; + } /* end seed */ + + #endif + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/sethand.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/sethand.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/sethand.c Tue Oct 5 14:42:16 2004 *************** *** 0 **** --- 1,103 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define BLACK 2 + + extern unsigned char p[19][19]; + + void sethand(int i) + /* set up handicap pieces */ + { + if (i > 0) + { + p[3][3] = BLACK; + if (i > 1) + { + p[15][15] = BLACK; + if (i > 2) + { + p[3][15] = BLACK; + if (i > 3) + { + p[15][3] = BLACK; + if (i == 5) + p[9][9] = BLACK; + else + if (i > 5) + { + p[9][15] = BLACK; + p[9][3] = BLACK; + if (i == 7) + p[9][9] = BLACK; + else + if (i > 7) + { + p[15][9] = BLACK; + p[3][9] = BLACK; + if (i > 8) + p[9][9] = BLACK; + if (i > 9) + {p[2][2] = 2; + if (i > 10) + {p[16][16] = 2; + if (i > 11) + {p[2][16] = 2; + if (i > 12) + {p[16][2] = 2; + if (i > 13) + {p[6][6] = 2; + if (i > 14) + {p[12][12] = 2; + if (i > 15) + {p[6][12] = 2; + if (i > 16) + p[12][6] = 2; + } + } + } + } + } + } + } + } + } + } + } + } + } + } /* end sethand */ + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/showbord.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/showbord.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/showbord.c Tue Oct 5 14:42:16 2004 *************** *** 0 **** --- 1,290 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + #define WHITE 1 + + extern unsigned char p[19][19]; + extern int mymove, umove; + extern int mk, uk; /* piece captured */ + + void showboard(void) + /* show go board */ + { + int i, j, ii; + + /* p = 0 for empty ,p = 1 for white piece, p = 2 for black piece */ + printf(" A B C D E F G H J K L M N O P Q R S T\n"); + /* row 19 to 17 */ + for (i = 0; i < 3; i++) + { + ii = 19 - i; + printf("%2d",ii); + + for (j = 0; j < 19; j++) + if (p[i][j] == EMPTY) + printf(" -"); + else if (p[i][j] == WHITE) + printf(" O"); + else printf(" X"); + + printf("%2d",ii); + printf("\n"); + } + /* row 16 */ + printf("16"); + + for (j = 0; j < 3; j++) + if (p[3][j] == EMPTY) + printf(" -"); + else if (p[3][j] == WHITE) + printf(" O"); + else printf(" X"); + + if (p[3][3] == 0) + printf(" +"); + else if (p[3][3] == WHITE) + printf(" O"); + else printf(" X"); + + for (j = 4; j < 9; j++) + if (p[3][j] == EMPTY) + printf(" -"); + else if (p[3][j] == WHITE) + printf(" O"); + else printf(" X"); + + if (p[3][9] == EMPTY) + printf(" +"); + else if (p[3][9] == WHITE) + printf(" O"); + else printf(" X"); + + for (j = 10; j < 15; j++) + if (p[3][j] == EMPTY) + printf(" -"); + else if (p[3][j] == WHITE) + printf(" O"); + else printf(" X"); + + if (p[3][15] == EMPTY) + printf(" +"); + else if (p[3][15] == WHITE) + printf(" O"); + else printf(" X"); + + for (j = 16; j < 19; j++) + if (p[3][j] == EMPTY) + printf(" -"); + else if (p[3][j] == WHITE) + printf(" O"); + else printf(" X"); + + printf("16"); + if (umove == 1) + printf(" Your color: White O\n"); + else + if (umove == 2) + printf(" Your color: Black X\n"); + else + printf("\n"); + /* row 15 to 11 */ + for (i = 4; i < 9; i++) + { + ii = 19 - i; + printf("%2d",ii); + + for (j = 0; j < 19; j++) + if (p[i][j] == EMPTY) + printf(" -"); + else if (p[i][j] == WHITE) + printf(" O"); + else printf(" X"); + + printf("%2d",ii); + if (i == 4) + { + if (mymove == 1) + printf(" My color: White O\n"); + else + if (mymove == 2) + printf(" My color: Black X\n"); + else + printf("\n"); + } + else + if (i != 8) + printf("\n"); + else + printf(" You have captured %d pieces\n", mk); + } + /* row 10 */ + printf("10"); + + for (j = 0; j < 3; j++) + if (p[9][j] == EMPTY) + printf(" -"); + else if (p[9][j] == WHITE) + printf(" O"); + else printf(" X"); + + if (p[9][3] == EMPTY) + printf(" +"); + else if (p[9][3] == WHITE) + printf(" O"); + else printf(" X"); + + for (j = 4; j < 9; j++) + if (p[9][j] == EMPTY) + printf(" -"); + else if (p[9][j] == WHITE) + printf(" O"); + else printf(" X"); + + if (p[9][9] == EMPTY) + printf(" +"); + else if (p[9][9] == WHITE) + printf(" O"); + else printf(" X"); + + for (j = 10; j < 15; j++) + if (p[9][j] == EMPTY) + printf(" -"); + else if (p[9][j] == WHITE) + printf(" O"); + else printf(" X"); + + if (p[9][15] == EMPTY) + printf(" +"); + else if (p[9][15] == WHITE) + printf(" O"); + else printf(" X"); + + for (j = 16; j < 19; j++) + if (p[9][j] == EMPTY) + printf(" -"); + else if (p[9][j] == WHITE) + printf(" O"); + else printf(" X"); + + printf("10"); + printf(" I have captured %d pieces\n", uk); + /* row 9 to 5 */ + for (i = 10; i < 15; i++) + { + ii = 19 - i; + printf("%2d",ii); + + for (j = 0; j < 19; j++) + if (p[i][j] == EMPTY) + printf(" -"); + else if (p[i][j] == WHITE) + printf(" O"); + else printf(" X"); + + printf("%2d",ii); + printf("\n"); + } + /* row 4 */ + printf(" 4"); + + for (j = 0; j < 3; j++) + if (p[15][j] == EMPTY) + printf(" -"); + else if (p[15][j] == WHITE) + printf(" O"); + else printf(" X"); + + if (p[15][3] == EMPTY) + printf(" +"); + else if (p[15][3] == WHITE) + printf(" O"); + else printf(" X"); + + for (j = 4; j < 9; j++) + if (p[15][j] == EMPTY) + printf(" -"); + else if (p[15][j] == WHITE) + printf(" O"); + else printf(" X"); + + if (p[15][9] == EMPTY) + printf(" +"); + else if (p[15][9] == WHITE) + printf(" O"); + else printf(" X"); + + for (j = 10; j < 15; j++) + if (p[15][j] == EMPTY) + printf(" -"); + else if (p[15][j] == WHITE) + printf(" O"); + else printf(" X"); + + if (p[15][15] == EMPTY) + printf(" +"); + else if (p[15][15] == WHITE) + printf(" O"); + else printf(" X"); + + for (j = 16; j < 19; j++) + if (p[15][j] == EMPTY) + printf(" -"); + else if (p[15][j] == WHITE) + printf(" O"); + else printf(" X"); + + printf(" 4"); + printf("\n"); + /* row 3 to 1 */ + for (i = 16; i < 19; i++) + { + ii = 19 - i; + printf("%2d",ii); + + for (j = 0; j < 19; j++) + if (p[i][j] == EMPTY) + printf(" -"); + else if (p[i][j] == WHITE) + printf(" O"); + else printf(" X"); + + printf("%2d",ii); + printf("\n"); + } + printf(" A B C D E F G H J K L M N O P Q R S T\n\n"); + } /* end showboard */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/showinst.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/showinst.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/showinst.c Tue Oct 5 14:42:16 2004 *************** *** 0 **** --- 1,96 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #define SUN 68000 + + #include + + void showinst(void) + /* show program instructions */ + { + printf("XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOX"); + printf("OXOXOXOXOXOX\n"); + printf("O "); + printf(" O\n"); + printf("X GNU GO (Previously Hugo) "); + printf(" X\n"); + printf("O the game of Go (Wei-Chi) "); + printf(" O\n"); + printf("X "); + printf(" X\n"); + printf("O version 1.1 3-1-89 "); + printf(" O\n"); + printf("X Copyright (C) 1989 Free Software Foundation, Inc. "); + printf(" X\n"); + printf("O Author: Man L. Li "); + printf(" O\n"); + printf("X GNU GO comes with ABSOLUTELY NO WARRANTY; see COPYING for"); + printf(" X\n"); + printf("O detail. This is free software, and you are welcome to "); + printf(" O\n"); + printf("X redistribute it; see COPYING for copying conditions. "); + printf(" X\n"); + printf("O "); + printf(" O\n"); + + #ifdef SUN + + printf("X Please report all bugs, modifications, suggestions "); + printf(" X\n"); + printf("O to manli at cs.uh.edu (Internet) "); + printf(" O\n"); + + #endif + + printf("X "); + printf(" X\n"); + printf("OXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXO"); + printf("XOXOXOXOXOXO\n"); + printf("\n\n\n\n\n\n\n\nPress return to continue"); + getchar(); + printf("\n\nTo play this game first select number of handicap pieces (0 to"); + printf(" 17) for the\nblack side. Next choose your color (black or white)."); + printf(" To place your piece,\nenter your move as coordinate on the board"); + printf(" in column and row. The column\nis from 'A' to 'T'(excluding 'I')."); + printf(" The row is from 1 to 19.\n\nTo pass your move enter 'pass' for"); + printf(" your turn. After both you and the computer\npassed the game will"); + printf(" end. To save the board and exit enter 'save'. The game\nwill"); + printf(" continue the next time you start the program. To stop the game in"); + printf(" the\nmiddle of play enter 'stop' for your move. You will be"); + printf(" asked whether you want\nto count the result of the game. If you"); + printf(" answer 'y' then you need to remove the\nremaining dead pieces and"); + printf(" fill up neutral turf on the board as instructed.\nFinally, the"); + printf(" computer will count all pieces for both side and show the result.\n\n"); + } /* end showinst */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/suicide.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/suicide.c:1.1 *** /dev/null Tue Oct 5 14:42:27 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/gnugo/suicide.c Tue Oct 5 14:42:16 2004 *************** *** 0 **** --- 1,84 ---- + /* + GNU GO - the game of Go (Wei-Chi) + Version 1.1 last revised 3-1-89 + Copyright (C) Free Software Foundation, Inc. + written by Man L. Li + modified by Wayne Iba + documented by Bob Webber + */ + /* + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation - version 1. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License in file COPYING for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Please report any bug/fix, modification, suggestion to + + mail address: Man L. Li + Dept. of Computer Science + University of Houston + 4800 Calhoun Road + Houston, TX 77004 + + e-mail address: manli at cs.uh.edu (Internet) + coscgbn at uhvax1.bitnet (BITNET) + 70070,404 (CompuServe) + */ + + #include + + #define EMPTY 0 + + extern unsigned char p[19][19], l[19][19]; + extern int mymove, umove; + extern int lib; + extern int uik, ujk; /* piece captured */ + + extern void countlib(int m, int n, int color); + extern void eval(int color); + + int suicide(int i, int j) + /* check for suicide move of opponent at p[i][j] */ + { + int m, n, k; + + /* check liberty of new move */ + lib = 0; + countlib(i, j, umove); + if (lib == 0) + /* new move is suicide then check if kill my pieces and Ko possibility */ + { + /* assume alive */ + p[i][j] = umove; + + /* check my pieces */ + eval(mymove); + k = 0; + + for (m = 0; m < 19; m++) + for (n = 0; n < 19; n++) + /* count pieces will be killed */ + if ((p[m][n] == mymove) && !l[m][n]) ++k; + + if ((k == 0) || (k == 1 && ((i == uik) && (j == ujk)))) + /* either no effect on my pieces or an illegal Ko take back */ + { + p[i][j] = EMPTY; /* restore to open */ + return 1; + } + else + /* good move */ + return 0; + } + else + /* valid move */ + return 0; + } /* end suicide */ From lattner at cs.uiuc.edu Tue Oct 5 15:08:38 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 15:08:38 -0500 Subject: [llvm-commits] CVS: llvm-test/SingleSource/Benchmarks/Misc/queens.c Message-ID: <200410052008.PAA25683@apoc.cs.uiuc.edu> Changes in directory llvm-test/SingleSource/Benchmarks/Misc: queens.c added (r1.1) --- Log message: New testcase --- Diffs of the changes: (+366 -0) Index: llvm-test/SingleSource/Benchmarks/Misc/queens.c diff -c /dev/null llvm-test/SingleSource/Benchmarks/Misc/queens.c:1.1 *** /dev/null Tue Oct 5 15:08:37 2004 --- llvm-test/SingleSource/Benchmarks/Misc/queens.c Tue Oct 5 15:08:27 2004 *************** *** 0 **** --- 1,366 ---- + /* + ** queens.c -- Find solutions to the Eight-Queens chess problem. + ** Roberto Sierra 3/19/84 Version 1.1 + ** + ** Description: + ** This program finds all the possible ways that N queens can + ** be placed on an NxN chessboard so that the queens cannot + ** capture one another -- that is, so that no rank, file or + ** diagonal is occupied by more than one queen. By default, + ** the program prints the first solution it finds. You can + ** use the -a option to print all solutions, or the -c option + ** just to count them. The program allows the chess board + ** to be from 1x1 (trivial case) to 100x100. Warning: the + ** larger the chess board, the longer it typically takes to + ** find each solution, even though there may be more of them. + ** + ** This is a terrific example of the utility of recursion. The + ** algorithm uses recursion to drastically limit the number + ** of board positions that are tested. The program is able + ** to find all 8x8 queen solutions in a fraction of a second + ** (not counting print time). The code makes no attempt to + ** eliminate symmetrical solutions, so the number of solutions + ** reported will always be higher than the actual number of + ** distinct solutions. + ** + ** + ** Usage: + ** queens [-ac] n + ** + ** n Number of queens (rows and columns). An integer from 1 to 100. + ** -a Find and print all solutions. + ** -c Count all solutions, but do not print them. + ** + ** The output is sent to stdout. All errors messages are + ** sent to stderr. If a problem arises, the return code is -1. + ** + ** + ** Examples: + ** + ** queens 8 ## Show an 8x8 solution + ** 8 queens on a 8x8 board... + ** Q - - - - - - - + ** - - - - Q - - - + ** - - - - - - - Q + ** - - - - - Q - - + ** - - Q - - - - - + ** - - - - - - Q - + ** - Q - - - - - - + ** - - - Q - - - - + ** + ** queens -c 8 ## Count all 8x8 solutions + ** 8 queens on a 8x8 board... + ** ...there are 92 solutions. + ** + ** queens -a 4 ## Show all 4x4 solutions + ** 4 queens on a 4x4 board... + ** + ** Solution #1: + ** - Q - - + ** - - - Q + ** Q - - - + ** - - Q - + ** + ** Solution #2: + ** - - Q - + ** Q - - - + ** - - - Q + ** - Q - - + ** + ** ...there are 2 solutions. + ** + ** + ** Build Instructions: + ** You'll need an ANSI C compiler (or the willingness to edit + ** the program a bit). If you've got Gnu C, then you can + ** compile and load the program as follows: + ** + ** gcc queens.c -ansi -o queens + ** + ** [If you're using MPW on the Mac, define '-d MPW' on the + ** compile line so that background processing will occur.] + ** + ** + ** Algorithm: + ** In a 1984 Byte article, I ran across an interesting letter + ** from a high school student who was attempting to solve the + ** Eight Queens problem using a BASIC interpreter. He had + ** developed a program which placed eight queens successively + ** on all sixty-four squares, testing for conflicts at each + ** iteration. Of course, such a program would require 64^8 + ** iterations (about 2.8x10^14 iterations). Even in C on a, + ** fast CPU, this could take months or years. Byte's answer was + ** to alter the loops so that the queens resided on separate + ** ranks, thereby reducing the number of iterations required + ** to find all solutions to 8^8 iterations (about 16 million). + ** More reasonable, but still requiring a chunk of CPU time. + ** + ** I puzzled about this problem a bit, and came to realize that + ** this was still wasting a lot of CPU cycles. Though I'm sure + ** others have come up with good algorithms, I decided to come + ** up with my own, with a particular eye on efficiency. The + ** resulting algorithm finds all 8x8 solutions in a fraction + ** of a second (there are 92 solutions, including rotations). + ** On a Sun 4, it'll find all 365,596 solutions on a 14x14 board + ** in a bit over 2 minutes (printing them out requires extra + ** time, of course). Even Byte's solution would require 14^14 + ** iterations (about 10^16) which would take aeons. + ** + ** My algorithm works as follows: + ** (1) Place a queen in the top left corner. + ** (2) Place another queen immediately below. + ** (3) Test for conflicts. If the second queen conflicts (it + ** does at first), then move it one square to the right. + ** (4) Loop step 3 until there are no conflicts. Place + ** the next queen on the board and recurse. + ** (5) If any queen reaches the right edge of the board, + ** remove it and 'pop' to the previous recursion level. + ** (6) Now repeat these steps recursively until all eight + ** queens (or however many) have been placed without + ** conflict -- the result is a solution to the problem, + ** which is counted and optionally printed. + ** + ** Because conflicts are tested as the recursion proceeds, + ** this has the effect of 'pruning' the recursion so that + ** a large number of board positions are not even attempted. + ** The result is that the algorithm runs in reasonable time. + ** + ** I used a few tricks to make the test-for-conflict code + ** extremely efficient -- there is no 'inner' loop to search + ** along ranks, files, or diagonals. A series of arrays are + ** maintained instead which indicate which queen currently + ** 'owns' each rank, file or diagonal. This makes the + ** algorithm really fly, though the code is a little hard to + ** read. Lastly, pointer arithmetic is used to reduce the + ** number of implicit multiplications used in array addressing. + ** + ** + ** Contact: + ** For queries regarding this program, contact Roberto Sierra + ** at any of the following addresses: + ** + ** Roberto Sierra + ** bert at netcom.com (preferred address) + ** 73557.2101 at compuserve.com + ** + ** Tempered MicroDesigns + ** P.O. Box 170638 + ** San Francisco, CA 94117 + ** + ** + ** Fine Print: + ** This program is in the public domain and can be used for + ** any purpose whatsoever, including commercial application. + ** [I'd like to hear what you do with it, though.] + ** Absolutely no warranty or liability is implied or extended + ** by the author. + ** + ** + ** Modification History: + ** PRS 3/19/84 v1.0 -- Original version. + ** PRS 7/25/93 v1.1 -- ANSIfied the code. More efficient pointers. + */ + + + #include /* Need standard I/O functions */ + #include /* Need exit() routine interface */ + #include /* Need strcmp() interface */ + #ifdef MPW /* Macintosh MPW ONLY */ + # include /* Need cursor control interfaces */ + #endif + + #define MAXQUEENS 100 /* Max number of queens */ + #define MAXRANKS MAXQUEENS /* Max number of ranks (rows) */ + #define MAXFILES MAXQUEENS /* Max number of files (columns) */ + #define MAXDIAGS (MAXRANKS+MAXFILES-1) /* Max number of diagonals */ + #define EMPTY (MAXQUEENS+1) /* Marks unoccupied file or diagonal */ + + /* GLOBAL VARIABLES */ + + int queens; /* Number of queens to place */ + int ranks; /* Number of ranks (rows) */ + int files; /* Number of files (columns) */ + int printing = 1; /* TRUE if printing positions */ + int findall = 0; /* TRUE if finding all solutions */ + + unsigned long solutions = 0; /* Number of solutions found */ + int queen[MAXRANKS]; /* File on which each queen is located */ + int file[MAXFILES]; /* Which queen 'owns' each file */ + int fordiag[MAXDIAGS]; /* Which queen 'owns' forward diagonals */ + int bakdiag[MAXDIAGS]; /* Which queen 'owns' reverse diagonals */ + char *progname = NULL; /* The name of this program */ + + + /* -------------------------- PROTOTYPES ----------------------- */ + + void pboard(void); + void find(register int level); + + + /*-------------------------- main() ---------------------------- + ** MAIN program. The main purpose of this routine is to deal + ** with decoding the command line arguments, initializing the + ** various arrays, and starting the recursive search routine. + */ + void main(int argc, char **argv) + { + register int i; /* Loop variable */ + register char *p; /* Ptr to argument */ + char *usage = + "Usage: %s [-ac] n\n\ + \tn\tNumber of queens (rows and columns). An integer from 1 to 100.\n\ + \t-a\tFind and print all solutions.\n\ + \t-c\tCount all solutions, but do not print them.\n"; + + #ifdef MPW /* Macintosh MPW ONLY */ + InitCursorCtl(0); /* Enable cursor control */ + #endif + + progname = argv[0]; /* Name of the program */ + + /**** DECODE COMMAND LINE ARGUMENTS ****/ + printing = 0; + queens = 14; + findall = 1; + + for(i = 1; i < argc; ++i) { /* Scan through arguments */ + p = argv[i]; /* Ptr to base of argument */ + if(*p == '-') { /* Command line option? */ + while(*++p) { /* Loop through characters */ + switch(*p) { /* What is the character */ + case 'c': /* '-c' option */ + printing = 0; /* Counting, not printing */ + case 'a': /* '-a' option */ + findall = 1; /* Find all solutions */ + break; + default: /* Illegal option */ + fprintf(stderr,"%s: Illegal option '%s'\n",progname,argv[i]); + fprintf(stderr,usage,progname); + exit(-1); + } /* End of switch */ + } /* End of loop */ + } /* End of option test */ + else { + if(sscanf(p,"%d",&queens) != 1) { /* Read integer argument */ + fprintf(stderr,"%s: Non-integer argument '%s'\n",progname,p); + exit(-1); + } + if(queens <= 0) { /* N must be positive */ + fprintf(stderr,"%s: n must be positive integer\n",progname); + exit(-1); + } + if(queens > MAXQUEENS) { /* N can't be too large */ + fprintf(stderr,"%s: Can't have more than %d queens\n", + progname, MAXQUEENS); + exit(-1); + } + } /* End of argument test */ + } /* End of argument scan loop */ + if(!queens) { + fprintf(stderr,"%s: Missing n argument\n",progname); + fprintf(stderr,usage,progname); + exit(-1); + } + + ranks = files = queens; /* NxN board for N queens */ + printf("%d queen%s on a %dx%d board...\n", + queens, queens > 1 ? "s" : "", ranks, files); + fflush(stdout); + + /* Initialization */ + solutions = 0; /* No solutions yet */ + for(i = 0; i < MAXFILES; ++i) file[i] = EMPTY; + for(i = 0; i < MAXDIAGS; ++i) fordiag[i] = bakdiag[i] = EMPTY; + + /* Find all solutions (begin recursion) */ + find(0); + if(printing && solutions) putchar('\n'); + + /* Report results */ + if(solutions == 1) printf("...there is 1 solution\n"); + else printf("...there are %ld solutions\n", solutions); + + exit(0); /* No errors */ + } + + + /***********************/ + /**** ROUTINES ****/ + /***********************/ + + /*------------------------- pboard() --------------------------- + ** This routines prints the board for a particular solution. + ** The output is sent to stdout. + */ + void pboard(void) + { + register int i, j; /* Rank/File indices */ + + if(findall) /* Only if searching for all */ + printf("\nSolution #%lu:\n",solutions); /* Print solution number */ + + for(i = 0; i < ranks; ++i) { /* Loop through all ranks */ + for(j = 0; j < files; ++j) { /* Loop through all files */ + putchar(' '); /* Output a space */ + if(j == queen[i]) putchar('Q'); /* Output Q for queen... */ + else putchar('-'); /* or '-' if empty */ + } + putchar('\n'); /* Break line */ + } + fflush(stdout); /* Flush solution to output */ + } + + + /*-------------------------- find() ---------------------------- + ** FIND is the recursive heart of the program, and finds all + ** solutions given a set of level-1 fixed queen positions. + ** The routine moves a single queen through all files (columns) + ** at the current rank (recursion level). As the queen is moved, + ** conflict tests are made. If the queen can be placed without + ** conflict, then the routine recurses to the next level. When + ** all queens have been placed without conflict, a solution is + ** counted and reported. + */ + void find(register int level) + { + register int f; /* Indexes through files */ + register int *fp, *fdp, *bdp; /* Ptrs to file/diagonal entries */ + + #ifdef MPW /* Macintosh MPW ONLY */ + if(level & 7 == 0) /* Periodically break for... */ + SpinCursor(1); /* background processing */ + #endif + + if(level == queens) { /* Placed all queens? Stop. */ + ++solutions; /* This is a solution! */ + if(printing) pboard(); /* Print board if printing */ + if(!findall) exit(0); /* May stop after first solution */ + #ifdef MPW /* Macintosh MPW ONLY */ + SpinCursor(1); /* background processing */ + #endif + } + else { /* Not at final level yet */ + for( /* Move queen through all files */ + f = 0, /* Queen starts at left (file 0) */ + fp = file, /* Ptr to base of file array */ + fdp = &fordiag[level], /* Ptr to first fwd diag entry */ + bdp = &bakdiag[level+files-1] /* Ptr to first bak diag entry */ + ; + f < files /* Loop through all files */ + ; + ++f, /* Advance index */ + ++fp, ++fdp, --bdp /* Advance pointers */ + ) { + if(*fp >= level && /* No queen on the file? */ + *fdp >= level && *bdp >= level /* No queens on diagonals? */ + ) { + queen[level] = f; /* Note new position of queen */ + *fp = *fdp = *bdp = level; /* Place queen on file & diags */ + find(level+1); /* This level OK, recurse to next */ + *fp = *fdp = *bdp = EMPTY; /* Remove queen from file & diags */ + } /* End of conflict test */ + } /* End of file loop */ + } /* End if (level == queens) */ + } + + From gaeke at cs.uiuc.edu Tue Oct 5 15:39:10 2004 From: gaeke at cs.uiuc.edu (Brian Gaeke) Date: Tue, 5 Oct 2004 15:39:10 -0500 Subject: [llvm-commits] CVS: reopt/lib/Makefile Message-ID: <200410052039.PAA32033@zion.cs.uiuc.edu> Changes in directory reopt/lib: Makefile updated: 1.25 -> 1.26 --- Log message: Only build the WholeReoptimizer dir if not on PPC. --- Diffs of the changes: (+2 -2) Index: reopt/lib/Makefile diff -u reopt/lib/Makefile:1.25 reopt/lib/Makefile:1.26 --- reopt/lib/Makefile:1.25 Mon Oct 4 16:33:39 2004 +++ reopt/lib/Makefile Tue Oct 5 15:38:58 2004 @@ -1,11 +1,11 @@ LEVEL = .. -DIRS := BinInterface Mapping TraceCache Trigger LightWtProfiling Inst Optimizations TraceToFunction TraceJIT TraceIO WholeReoptimizer +DIRS := BinInterface Mapping TraceCache Trigger LightWtProfiling Inst Optimizations TraceToFunction TraceJIT TraceIO include $(LEVEL)/Makefile.config # Mac OS X assembler doesn't love the dummy function. ifneq ($(ARCH),PowerPC) -DIRS := ScratchMemory $(DIRS) +DIRS := ScratchMemory $(DIRS) WholeReoptimizer endif include $(LEVEL)/Makefile.common From lattner at cs.uiuc.edu Tue Oct 5 15:58:37 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 15:58:37 -0500 Subject: [llvm-commits] CVS: llvm-test/SingleSource/Benchmarks/McGill/ Message-ID: <200410052058.PAA26711@apoc.cs.uiuc.edu> Changes in directory llvm-test/SingleSource/Benchmarks/McGill: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/SingleSource/Benchmarks/McGill added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 15:58:50 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 15:58:50 -0500 Subject: [llvm-commits] CVS: llvm-test/SingleSource/Benchmarks/McGill/Makefile README.txt chomp.c exptree.c misr.c queens.c Message-ID: <200410052058.PAA26731@apoc.cs.uiuc.edu> Changes in directory llvm-test/SingleSource/Benchmarks/McGill: Makefile added (r1.1) README.txt added (r1.1) chomp.c added (r1.1) exptree.c added (r1.1) misr.c added (r1.1) queens.c added (r1.1) --- Log message: New benchmarks --- Diffs of the changes: (+1466 -0) Index: llvm-test/SingleSource/Benchmarks/McGill/Makefile diff -c /dev/null llvm-test/SingleSource/Benchmarks/McGill/Makefile:1.1 *** /dev/null Tue Oct 5 15:58:47 2004 --- llvm-test/SingleSource/Benchmarks/McGill/Makefile Tue Oct 5 15:58:37 2004 *************** *** 0 **** --- 1,5 ---- + LEVEL = ../../.. + LDFLAGS += -lm + FP_TOLERANCE := 0.001 + + include $(LEVEL)/SingleSource/Makefile.singlesrc Index: llvm-test/SingleSource/Benchmarks/McGill/README.txt diff -c /dev/null llvm-test/SingleSource/Benchmarks/McGill/README.txt:1.1 *** /dev/null Tue Oct 5 15:58:50 2004 --- llvm-test/SingleSource/Benchmarks/McGill/README.txt Tue Oct 5 15:58:37 2004 *************** *** 0 **** --- 1,3 ---- + These benchmarks were downloaded from: + http://www.prolangs.rutgers.edu/public.html + Index: llvm-test/SingleSource/Benchmarks/McGill/chomp.c diff -c /dev/null llvm-test/SingleSource/Benchmarks/McGill/chomp.c:1.1 *** /dev/null Tue Oct 5 15:58:50 2004 --- llvm-test/SingleSource/Benchmarks/McGill/chomp.c Tue Oct 5 15:58:37 2004 *************** *** 0 **** --- 1,424 ---- + #include + #include + + #define NDATA (int *)malloc(ncol * sizeof(int)) + #define NLIST (struct _list *)malloc(sizeof(struct _list)) + #define NPLAY (struct _play *)malloc(sizeof(struct _play)) + + struct _list + { + int *data; + struct _list *next; + } *wanted; + + struct _play + { + int value; + int *state; + struct _list *first; + struct _play *next; + } *game_tree; + + int nrow,ncol; /* global so as to avoid passing them all over the place */ + + int *copy_data(data) /* creates a duplicate of a given -data list */ + int *data; + { + int *new = NDATA; + int counter = ncol; + while (counter --) + new[counter] = data[counter]; + return new; + } + + int next_data(int *data) /* gives the next logical setup to the one passed */ + /* new setup replaces the old. Returns 0 if no valid */ + { /* setup exists after the one passed */ + int counter = 0; + int valid = 0; /* default to none */ + while ((counter != ncol) && (! valid)) /* until its done */ + { + if (data[counter] == nrow) /* if we hit a border */ + { + data[counter] = 0; /* reset it to zero */ + counter ++; /* and take next column */ + } + else + { + data[counter] ++; /* otherwise, just increment row number */ + valid = 1; /* and set valid to true. */ + } + } + return valid; /* return whether or not */ + } /* a next could be found */ + + void melt_data(int *data1,int *data2) /* melts 2 _data's into the first one. */ + { + int counter = ncol; + while (counter --) /* do every column */ + { + if (data1[counter] > data2[counter]) /* take the lowest one */ + data1[counter] = data2[counter]; /* and put in first _data */ + } + } + + int equal_data(int *data1,int *data2) /* check if both _data's are equal */ + { + int counter = ncol; + while ((counter --) && (data1[counter] == data2[counter])); + return (counter < 0); + } + + int valid_data(int *data) /* checks if the play could ever be achieved. */ + { + int low; /* var to hold the current height */ + int counter = 0; + low = nrow; /* default to top of board */ + while (counter != ncol) /* for every column */ + { + if (data[counter] > low) break; /* if you get something higher */ + low = data[counter]; /* set this as current height */ + counter ++; + } + return (counter == ncol); + } + + void dump_list(struct _list *list) /* same for a _list structure */ + { + if (list != NULL) + { + dump_list(list -> next); /* dump the rest of it */ + free(list -> data); /* and its _data structure */ + free(list); + } + } + + void dump_play(play) /* and for the entire game tree */ + struct _play *play; + { + if (play != NULL) + { + dump_play(play -> next); /* dump the rest of the _play */ + dump_list(play -> first); /* its _list */ + free(play -> state); /* and its _data */ + free(play); + } + } + + int get_value(int *data) /* get the value (0 or 1) for a specific _data */ + { + struct _play *search; + search = game_tree; /* start at the begginig */ + while (! equal_data(search -> state,data)) /* until you find a match */ + search = search -> next; /* take next element */ + return search -> value; /* return its value */ + } + + void show_data(int *data) /* little display routine to give off results */ + { + int counter = 0; + while (counter != ncol) + { + printf("%d",data[counter ++]); + if (counter != ncol) putchar(','); + } + } + + void show_move(int *data) /* puts in the "(" and ")" for show_data() */ + { + putchar('('); + show_data(data); + printf(")\n"); + } + + void show_list(struct _list *list) /* show the entire list of moves */ + { + while (list != NULL) + { + show_move(list -> data); + list = list -> next; + } + } + + void show_play(struct _play *play) /* to diplay the whole tree */ + { + while (play != NULL) + { + printf("For state :\n"); + show_data(play -> state); + printf(" value = %d\n",play -> value); + printf("We get, in order :\n"); + show_list(play -> first); + play = play -> next; + } + } + + int in_wanted(int *data) /* checks if the current _data is in the wanted list */ + { + struct _list *current; + current = wanted; /* start at the begginig */ + while (current != NULL) /* unitl the last one */ + { + if (equal_data(current -> data,data)) break; /* break if found */ + current = current -> next; /* take next element */ + } + if (current == NULL) return 0; /* if at the end, not found */ + return 1; + } + + int *make_data(int row,int col) /* creates a new _data with the correct */ + /* contents for the specified row & col */ + { + int count; + int *new = NDATA; + for (count = 0;count != col;count ++) /* creates col-1 cells with nrow */ + new[count] = nrow; + for (;count != ncol;count ++) /* and the rest with row as value */ + new[count] = row; + return new; /* and return pointer to first element */ + } + + struct _list *make_list(int *data,int *value,int *all) /* create the whole _list of moves */ + /* for the _data structure data */ + { + int row,col; + int *temp; + struct _list *head,*current; + *value = 1; /* set to not good to give */ + head = NLIST; /* create dummy header */ + head -> next = NULL; /* set NULL as next element */ + current = head; /* start from here */ + for (row = 0;row != nrow;row ++) /* for every row */ + { + for (col = 0;col != ncol;col ++) /* for every column */ + { + temp = make_data(row,col); /* create _data for this play */ + melt_data(temp,data); /* melt it with the current one */ + if (! equal_data(temp,data)) /* if they are different, it good */ + { + current -> next = NLIST; /* create new element in list */ + current -> next -> data = copy_data(temp); /* copy data, and place in list */ + current -> next -> next = NULL; /* NULL the next element */ + current = current -> next; /* advance pointer */ + if (*value == 1) /* if still not found a good one */ + *value = get_value(temp); /* look at this value */ + if ((! *all) && (*value == 0)) + { /* if we found it, and all is not set */ + col = ncol - 1; /* do what it take sto break out now */ + row = nrow - 1; + if (in_wanted(temp)) /* if in the wanted list */ + *all = 2; /* flag it */ + } + } + else /* if its not a valid move */ + { + if (col == 0) row = nrow - 1; /* break out if at first column */ + col = ncol - 1; /* but make sure you break out */ + } /* of the col for-loop anyway */ + free(temp); /* dump this unneeded space */ + } + } + current = head -> next; /* skip first element */ + free(head); /* dump it */ + if (current != NULL) *value = 1 - *value; /* invert value if its */ + return current; /* not the empty board */ + } + + struct _play *make_play(int all) /* make up the entire tree-like stuff */ + { + int val; + int *temp; + struct _play *head,*current; + head = NPLAY; /* dummy header again */ + current = head; /* start here */ + game_tree = NULL; /* no elements yet */ + temp = make_data(0,0); /* new data, for empty board */ + temp[0] --; /* set it up at (-1,xx) so that next_data() returns (0,xx) */ + while (next_data(temp)) /* take next one, and break if none */ + { + if (valid_data(temp)) /* if board position is possible */ + { + current -> next = NPLAY; /* create a new _play cell */ + if (game_tree == NULL) game_tree = current -> next; + /* set up game_tree if it was previously NULL */ + current -> next -> state = copy_data(temp); /* make a copy of temp */ + current -> next -> first = make_list(temp,&val,&all); + /* make up its whole list of possible moves */ + current -> next -> value = val; /* place its value */ + current -> next -> next = NULL; /* no next element */ + current = current -> next; /* advance pointer */ + if (all == 2) /* if found flag is on */ + { + free(temp); /* dump current temp */ + temp = make_data(nrow,ncol); /* and create one that will break */ + } + } + } + current = head -> next; /* skip first element */ + free(head); /* dump it */ + return current; /* and return pointer to start of list */ + } + + void make_wanted(int *data) /* makes up the list of positions from the full board */ + { + /* everything here is almost like in the previous function. */ + /* The reason its here, is that it does not do as much as */ + /* the one before, and thus goes faster. Also, it saves the */ + /* results directly in wanted, which is a global variable. */ + + int row,col; + int *temp; + struct _list *head,*current; + head = NLIST; + head -> next = NULL; + current = head; + for (row = 0;row != nrow;row ++) + { + for (col = 0;col != ncol;col ++) + { + temp = make_data(row,col); + melt_data(temp,data); + if (! equal_data(temp,data)) + { + current -> next = NLIST; + current -> next -> data = copy_data(temp); + current -> next -> next = NULL; + current = current -> next; + } + else + { + if (col == 0) row = nrow - 1; + col = ncol - 1; + } + free(temp); + } + } + current = head -> next; + free(head); + wanted = current; + } + + int *get_good_move(struct _list *list) /* gets the first good move from a _list */ + { + if (list == NULL) return NULL; /* if list is NULL, say so */ + /* until end-of-list or a good one is found */ + /* a good move is one that gives off a zero value */ + while ((list -> next != NULL) && (get_value(list -> data))) + list = list -> next; + return copy_data(list -> data); /* return the value */ + } + + int *get_winning_move(struct _play *play) /* just scans for the first good move */ + /* in the last _list of a _play. This */ + { /* is the full board */ + int *temp; + while (play -> next != NULL) play = play -> next; /* go to end of _play */ + temp = get_good_move(play -> first); /* get good move */ + return temp; /* return it */ + } + + struct _list *where(int *data,struct _play *play) + { + while (! equal_data(play -> state,data)) /* search for given _data */ + play = play -> next; + return play -> first; /* return the pointer */ + } + + void get_real_move(int *data1,int *data2,int *row,int *col) /* returns row & col of the move */ + /* which created data1 from data2 */ + { + *col = 0; + while (data1[*col] == data2[*col]) /* until there is a change */ + (*col) ++; /* and increment col number */ + *row = data1[*col]; /* row is given by the content of the structure */ + } + + void main(void) + { + int row,col,maxrow,player; + int *win,*current,*temp; + struct _play *tree,*look; + /* allow user to select mode */ + printf("Mode : 1 -> multiple first moves\n"); + printf(" 2 -> report game\n"); + printf(" 3 -> good positions\n"); + printf(" Selection : "); + #if 0 + scanf("%d",&row); /* put it in row for now */ + #else + row = 2; + #endif + switch (row) + { + case 1: + printf("Enter number of Columns : "); + scanf("%d",&ncol); + printf("Enter Initial number of Rows : "); + scanf("%d",&nrow); + printf("Enter Maximum number of Rows : "); + scanf("%d",&maxrow); + for (;nrow <= maxrow;nrow ++) + { + make_wanted(make_data(nrow,ncol)); /* created wanted list */ + tree = make_play(0); /* create tree */ + win = get_winning_move(tree); /* get the winning move */ + /* get the coordinates of this move */ + get_real_move(win,make_data(nrow,ncol),&row,&col); + /* print it out nicely */ + printf("The winning initial move for %d x %d CHOMP is (%d,%d)\n",nrow,ncol,row,col); + dump_play(tree); /* dump for memory management */ + dump_list(wanted); + } + break; + case 2: + printf("Enter number of Columns : "); + #if 0 + scanf("%d",&ncol); + #else + ncol = 7; + #endif + printf("Enter number of Rows : "); + #if 0 + scanf("%d",&nrow); + #else + nrow = 8; + #endif + tree = make_play(1); /* create entire tree structure, not just the */ + player = 0; /* needed part for first move */ + current = make_data(nrow,ncol); /* start play at full board */ + while (current != NULL) + { + temp = get_good_move(where(current,tree)); /* get best move */ + if (temp != NULL) /* temp = NULL when the poison pill is taken */ + { + get_real_move(temp,current,&row,&col); /* calculate coordinates */ + /* print it out nicely */ + printf("player %d plays at (%d,%d)\n",player,row,col); + player = 1 - player; /* next player to do the same */ + free(current); /* dump for memory management */ + } + current = temp; /* update board */ + } + dump_play(tree); /* dump unneeded tree */ + printf("player %d loses\n",1 - player); /* display winning player */ + break; + case 3: + printf("Enter number of Columns : "); + scanf("%d",&ncol); + printf("Enter number of Rows : "); + scanf("%d",&nrow); + printf("ATTENTION : representation is as in a _data structure\n"); + tree = make_play(1); /* create tree */ + look = tree; /* start here */ + while (look != NULL) + { + if (look -> value == 0) /* show all positions bad for player 2 */ + show_move(look -> state); /* i.e. bad positions to be in */ + look = look -> next; /* with zero value */ + } + dump_play(tree); /* dump for memory management */ + break; + } + } + + /*****************************************************************************/ Index: llvm-test/SingleSource/Benchmarks/McGill/exptree.c diff -c /dev/null llvm-test/SingleSource/Benchmarks/McGill/exptree.c:1.1 *** /dev/null Tue Oct 5 15:58:50 2004 --- llvm-test/SingleSource/Benchmarks/McGill/exptree.c Tue Oct 5 15:58:37 2004 *************** *** 0 **** --- 1,388 ---- + /*************************************************************************** + + PART 1: PROGRAM + + Pierre Ouellet ID 9009791 + + The problem solved by this program is stated as follows: + + Given a set S of k nonzero natural numbers, labeled n1..nk, + a "total" t, which is also a nonzero natural number, find + an expression tree, whose leaves are taken from S, and whose + interior nodes are each labeled one of {+, -, *, /}, and that + evaluates to t. There is the additional restriction that any + subtree must evaluate to a natural number greater than 0. + Division is permitted only if the value of the left child + is exactly divisible by the value of the right child. Also, + numbers in S may not be used more times than they appear, + e.g. if S = { 2, 3, 3 }, "3" may be used at most twice. + + The program uses a brute-force search, more precisely an + iterative deepening depth-first search. The search can be + viewed as an attempt to build the tree bottom-up: whenever + the value t is not present, we try to obtain it by "combining" + two available values, which are taken from the "work list", + which consists of those elements of S not yet used and the values + obtained by previous combinations. This is the equivalent of + creating a new root and making the two operands its children. + + The work list is an array of integers, originally containing + the elements of S. When elements are combined, they're marked + used and the result of combining them (the result of evaluating + the new root) is added at the end of the list. + + The combinations are saved in an array of Comb, to be printed out + when a solution is found. + + ***************************************************************************/ + + #include + #include + + #define NOOP 0 + #define ADD 1 + #define SUB 2 + #define MUL 3 + #define DIV 4 + + typedef struct + { + int operand1, operand2; + int operation; + + } Comb; + + /* Global variables are used to save time during the search */ + + static int goal; /* the value of t explained above */ + static int listLength; /* |S| */ + static int *workList; + static Comb *combList; + static Comb *solution; + static int best = 0; /* value of best solution found yet */ + static int dmax; /* maximal depth of search */ + static int stopSearch; /* flag so we stop at first solution */ + static int bestDepth = 0; /* depth of best solution; used if no exact + solution is found */ + static int nbNodes; /* statistics: number of nodes examined + (number of calls to recSearch) */ + + /************************* INITIALIZATION STUFF *************************/ + + int *newWorkList( int length ) + + /* Create a "work list", which is an array of integers with length + elements + */ + + { + int *newList = (int *) calloc( length, sizeof( int ) ); + + if( newList ) return newList; + + else + { + fprintf( stderr, "Out of memory for work list\n" ); + exit( 1 ); + } + } + + Comb *newCombList( int length ) + + /* Create a "combination list", which is to be used all the way through + the search. It contains the combinations attempted so far in the search. + */ + + { + Comb *newList = (Comb *) calloc( length, sizeof( Comb ) ); + + if( newList ) return newList; + + else + { + fprintf( stderr, "Out of memory for combination list\n" ); + exit( 1 ); + } + } + + void initWorkList( int *workList, int *givenList, int length ) + + { + int i; + + for( i = 0; i < length; i++ ) + workList[i] = givenList[i]; + } + + void initCombList( Comb *combList, int length ) + { + int i; + + for( i = 0; i < length; i++ ) + combList[i].operation = NOOP; + } + + /************************* AUXILIARY FUNCTIONS *************************/ + + void saveSolution( Comb *sol, Comb *combList, int length ) + + /* Copy a sequence of combinations. + */ + + { + int i; + + for( i = 0; i < length; i++ ) + { + sol[i].operand1 = combList[i].operand1; + sol[i].operand2 = combList[i].operand2; + sol[i].operation = combList[i].operation; + } + + sol[length].operation = NOOP; /* End marker */ + + } + + int calculate( Comb *comb ) + + /* Compute the value generated by a combination. + */ + + { + switch( comb->operation ) + { + case ADD: return comb->operand1 + comb->operand2; + case SUB: return comb->operand1 - comb->operand2; + case MUL: return comb->operand1 * comb->operand2; + case DIV: return comb->operand1 / comb->operand2; + + default: return 0; + } + } + + /************************* OUTPUT STUFF *************************/ + + void printSolution( Comb *combList, int length ) + { + int i; + + for( i = 0; i < length; i++ ) + { + printf( "%d", combList[i].operand1 ); + + switch( combList[i].operation ) + { + case NOOP: printf( " " ); break; + case ADD: printf( "+" ); break; + case SUB: printf( "-" ); break; + case MUL: printf( "*" ); break; + case DIV: printf( ":" ); break; + + default: printf( " d%d ", combList[i].operation ); + } + + printf( "%d=%d", combList[i].operand2, calculate( &combList[i] ) ); + + if( i < length - 1 ) printf( "; " ); else printf( ".\n" ); + } + + printf( "\n" ); + } + + void printList( int *list, int length, int mask ) + { + int i; + + for( i = 0; i < length; i++ ) + { + if( ( 1 << i ) & mask ) continue; + + printf( "%d ", list[i] ); + } + + printf( "\n" ); + } + + /************************* ACTUAL SEARCH STUFF *************************/ + + void recSearch( int searchDepth, int usedMask ) + + /* searchDepth: current depth within the search. + usedMask: used to tell which elements of the work list + have been used. + */ + + { + int currOp; /* current operation under consideration */ + int newMask; /* or'ed with old mask to mark used numbers from work list */ + int operand1; /* offset of operand 1 of combination within work list */ + int operand2; /* offset of operand 2 of combination within work list */ + + if( stopSearch ) return; /* unroll recursion when solution is found */ + + nbNodes++; /* Statistics */ + + if( searchDepth == dmax ) + { + /* check whether last number generated is nearer to t than best */ + if( abs( workList[listLength + searchDepth - 1] - goal ) + < abs( best - goal ) ) + { + /* if so, save solution */ + best = workList[listLength + searchDepth - 1]; + bestDepth = searchDepth; + saveSolution( solution, combList, searchDepth ); + + if( best == goal ) + { + printSolution( combList, searchDepth ); + stopSearch = 1; + } + } + } + + else + { + int working1, working2; /* hold values of numbers considered + for combination */ + int temp; /* for swapping */ + + /* iterate over all four operators {+, -, *, /} */ + for( currOp = ADD; currOp <= DIV; currOp++ ) + { + for( operand1 = 0; operand1 < listLength + searchDepth; + operand1++ ) + { + /* do not use already used numbers */ + if( ( 1 << operand1 ) & usedMask ) continue; + + for( operand2 = 0; operand2 < operand1; operand2++ ) + { + if( ( 1 << operand2 ) & usedMask ) continue; + + working1 = workList[operand1]; + working2 = workList[operand2]; + + /* x * 1 = 1 * x = x; x / 1 = x */ + if( ( currOp == MUL || currOp == DIV ) && + ( working1 == 1 || working2 == 1 ) ) continue; + + /* could arise from combination a - a for some a */ + if( working1 == 0 || working2 == 0 ) continue; + + /* make dure operand2 divides operand1 */ + if( currOp == DIV && + ( working1 % working2 ) ) continue; + + /* make sure operand1 >= operand2 for subtraction and + division */ + if( ( currOp == DIV || currOp == SUB ) && + ( working1 < working2 ) ) + { + temp = working1; + working1 = working2; + working2 = temp; + } + + /* mark operands used */ + newMask = usedMask | + ( 1 << operand1 ) | + ( 1 << operand2 ); + + /* save current combination */ + combList[searchDepth].operand1 = + working1; + combList[searchDepth].operand2 = + working2; + combList[searchDepth].operation = currOp; + + workList[listLength + searchDepth] = + calculate( &combList[searchDepth] ); + + /* search deeper */ + recSearch( searchDepth + 1, newMask ); + } + } + } + } + } + + void doSearch(void) + + /* Preliminary search. Takes care of the special case where |S| = 1 + and the only element of S is t. + */ + { + int i; + + for( i = 0; i < listLength; i++ ) + if( abs( workList[i] - goal ) < abs( best - goal ) ) + { + best = workList[i]; + } + + if( best == goal ) + { + printf( ".\n" ); + return; + } + + for( dmax = 1; dmax < listLength; dmax++ ) + { + recSearch( 0, 0 ); + + if( stopSearch ) break; + } + + /* If no exact solution was found */ + if( stopSearch == 0 ) + printSolution( solution, bestDepth ); + } + + int getInput(void) + { + int nums[16]; + int i = 0; + int c; + nums[0] = 13; + nums[1] = 32; + nums[2] = 14; + nums[3] = 1412; + + while( ( c = getchar() ) != '\n' && c != EOF ) + { + ungetc( c, stdin ); + fscanf( stdin, "%d", &nums[i] ); + i++; + } + + if( i == 0 ) i = 4; + + listLength = i - 1; + goal = nums[listLength]; + + workList = newWorkList( 2 * listLength ); + combList = newCombList( listLength ); + solution = newCombList( listLength ); + + initWorkList( workList, nums, listLength ); + initCombList( combList, listLength ); + initCombList( solution, listLength ); + + return( listLength ); + } + + void search(void) + { + /* set up global variables for search */ + stopSearch = 0; + nbNodes = 0; + + doSearch(); + } + + void main( int argc, char *argv[] ) + { + if( getInput() ) + search(); + } Index: llvm-test/SingleSource/Benchmarks/McGill/misr.c diff -c /dev/null llvm-test/SingleSource/Benchmarks/McGill/misr.c:1.1 *** /dev/null Tue Oct 5 15:58:50 2004 --- llvm-test/SingleSource/Benchmarks/McGill/misr.c Tue Oct 5 15:58:37 2004 *************** *** 0 **** --- 1,280 ---- + /* the name was converted to pgm5.c */ + /******************************************************* + + program: MISR.C + + + This program creates two MISR's one which contains the + true outputs and the other in which the outputs are + not currupted with the probability given in the input. + The values of the MISR's are compared to see if the + introduced errors have cancelled themselves. + + The usage is : MISR fileout reg_len #_vectors prob + #_times [structure] [seed] [seed] [seed]. + fileout has been nullified in this case to fit with + the description of the project. + reg_len is the length of the MISR's in considerstion. + #_vectors is the number of vectors to input to the + MISR's before checking to see of they are + identical. If '0', assume large value (infinite). + prob described above. + #_times is the number of times that the MISR's are + initialized and the experiment done before the + # of times outputs same/ # of times it is run + (#_times) is calculated. + [structure] gives the feedback structure of the MISR's. + if it is omitted, the situition where the end + feeds back to the beginning is used. + [seed]* is the seed to be used to initialize the random + generator. + *******************************************************/ + + #include + #include + #include + + #define INF 10000 + #define MAX_REG_LN 100 + #define BIN_MASK 1 + #define TRUE 1 + #define FALSE 0 + + int reg_len; + + typedef struct cells { + int f_free; + int faulty; + struct cells *next; + }misr_type; + + /* Prototypes */ + + int simulate(int iterations, misr_type *present, double prob, char *structure); + void init(misr_type *present); + void kill_list(misr_type *present); + void create_link_list(misr_type *cell_array); + + /* Main Program */ + + void main(int argc,char *argv[]) + { + misr_type cell_array; + int num_vect, num_times, num_true, i; + double prob; + char structure[MAX_REG_LN]; + unsigned short seed[3]; + + /* Check usage */ + if (0 && argc < 6) + { + printf("Usage: MISR fileout reg_len #_vectors prob #_times [structure] [seed] [seed] [seed]\n"); + return; + } + + /* input and translate arguments */ + /*sscanf(argv[2], "%lu", ®_len); + sscanf(argv[3], "%lu", &num_vect); + sscanf(argv[4], "%le", &prob); + sscanf(argv[5], "%lu", &num_times);*/ + + reg_len = num_vect = 10; + prob = .25; + num_times = 100000; + + + if (argc > 6) strcpy(structure, argv[6]); + else { + for (i=1; i 7) sscanf(argv[7], "%hu", &seed[0]); else seed[0] = 1; + if (argc > 8) sscanf(argv[8], "%hu", &seed[1]); else seed[1] = 0; + if (argc > 9) sscanf(argv[9], "%hu", &seed[2]); else seed[2] = 0; + + + /* Check validity of input */ + if (reg_len > MAX_REG_LN) + { + printf("Register too long; Max. = %d\n", MAX_REG_LN); + return; + } + if ((prob > 1) || (prob < 0)) + { + printf("Prob. out of range 0==1\n"); + return; + } + if (strlen(structure) != reg_len) + { + printf("Structure does not match Register length:\n"); + return; + } + + + /*initialize random f'n generator */ + seed48(seed); + + + /* create MISRs of reg_len length */ + create_link_list(&cell_array); + + /* simulate both circuits */ + num_true = 0; + if (num_vect != 0) + { + for (i=0; if_free = 1; + temp->faulty = 1; + temp->next = NULL; + present->next = temp; + present = present->next; + } + } + + + /************************************************************* + release linked list when finished + *************************************************************/ + void kill_list(misr_type *present) + { + misr_type *temp; + + while(present) + { + temp = present->next; + free(present); + present = temp; + } + return; + } + + + /************************************************************ + make both MISR's identical to start the experiment + ************************************************************/ + void init(misr_type *present) + { + + while(present->next != NULL) + { + present->faulty = present->f_free; + present = present->next; + } + } + + + /*********************************************************** + this proceedure is the workhorse of the program. Each time it + is called, it calculates the next value of each cell in the + MISR's and does this for hte number of times necessary. + ***********************************************************/ + int simulate(int iterations, misr_type *present, double prob, char *structure) + { + misr_type *temp; + int different, savef_free, savefaulty; + int rem, quot, h, i, j; + long rand; + double randprob; + + different = FALSE; + quot = (reg_len-1) / 31; + rem = (reg_len-1) % 31; + temp = present; + + for(h=0; hf_free; + savefaulty += temp->faulty; + } + temp->f_free = ((temp->next->f_free + rand) & BIN_MASK); + randprob = ((double)(lrand48() % 1000) / 1000); + if (prob > randprob) rand ^= BIN_MASK; + temp->faulty = ((temp->next->faulty + rand) & BIN_MASK); + temp = temp->next; + rand >>= 1; + } + } + rand = lrand48(); + for (j=0; jf_free; + savefaulty += temp->faulty; + } + temp->f_free = ((temp->next->f_free + rand) & BIN_MASK); + randprob = ((double)(lrand48() % 1000) / 1000); if (prob > randprob) rand ^= BIN_MASK; + temp->faulty = ((temp->next->faulty + rand) & BIN_MASK); + temp = temp->next; + rand >>= 1; + } + rand = lrand48(); + if (structure[reg_len - 1] == '1') + { + savef_free += temp->f_free; + savefaulty += temp->faulty; + } + temp->f_free = ((savef_free + rand) & BIN_MASK); + randprob = ((double)(lrand48() % 10000) / 10000); + if (prob > randprob) rand ^= BIN_MASK; + temp->faulty = ((savefaulty + rand) & BIN_MASK); + + temp = present; + } + + for (i=0; if_free != temp->faulty) different = TRUE; + temp = temp->next; + } + return different; + + } Index: llvm-test/SingleSource/Benchmarks/McGill/queens.c diff -c /dev/null llvm-test/SingleSource/Benchmarks/McGill/queens.c:1.1 *** /dev/null Tue Oct 5 15:58:50 2004 --- llvm-test/SingleSource/Benchmarks/McGill/queens.c Tue Oct 5 15:58:37 2004 *************** *** 0 **** --- 1,366 ---- + /* + ** queens.c -- Find solutions to the Eight-Queens chess problem. + ** Roberto Sierra 3/19/84 Version 1.1 + ** + ** Description: + ** This program finds all the possible ways that N queens can + ** be placed on an NxN chessboard so that the queens cannot + ** capture one another -- that is, so that no rank, file or + ** diagonal is occupied by more than one queen. By default, + ** the program prints the first solution it finds. You can + ** use the -a option to print all solutions, or the -c option + ** just to count them. The program allows the chess board + ** to be from 1x1 (trivial case) to 100x100. Warning: the + ** larger the chess board, the longer it typically takes to + ** find each solution, even though there may be more of them. + ** + ** This is a terrific example of the utility of recursion. The + ** algorithm uses recursion to drastically limit the number + ** of board positions that are tested. The program is able + ** to find all 8x8 queen solutions in a fraction of a second + ** (not counting print time). The code makes no attempt to + ** eliminate symmetrical solutions, so the number of solutions + ** reported will always be higher than the actual number of + ** distinct solutions. + ** + ** + ** Usage: + ** queens [-ac] n + ** + ** n Number of queens (rows and columns). An integer from 1 to 100. + ** -a Find and print all solutions. + ** -c Count all solutions, but do not print them. + ** + ** The output is sent to stdout. All errors messages are + ** sent to stderr. If a problem arises, the return code is -1. + ** + ** + ** Examples: + ** + ** queens 8 ## Show an 8x8 solution + ** 8 queens on a 8x8 board... + ** Q - - - - - - - + ** - - - - Q - - - + ** - - - - - - - Q + ** - - - - - Q - - + ** - - Q - - - - - + ** - - - - - - Q - + ** - Q - - - - - - + ** - - - Q - - - - + ** + ** queens -c 8 ## Count all 8x8 solutions + ** 8 queens on a 8x8 board... + ** ...there are 92 solutions. + ** + ** queens -a 4 ## Show all 4x4 solutions + ** 4 queens on a 4x4 board... + ** + ** Solution #1: + ** - Q - - + ** - - - Q + ** Q - - - + ** - - Q - + ** + ** Solution #2: + ** - - Q - + ** Q - - - + ** - - - Q + ** - Q - - + ** + ** ...there are 2 solutions. + ** + ** + ** Build Instructions: + ** You'll need an ANSI C compiler (or the willingness to edit + ** the program a bit). If you've got Gnu C, then you can + ** compile and load the program as follows: + ** + ** gcc queens.c -ansi -o queens + ** + ** [If you're using MPW on the Mac, define '-d MPW' on the + ** compile line so that background processing will occur.] + ** + ** + ** Algorithm: + ** In a 1984 Byte article, I ran across an interesting letter + ** from a high school student who was attempting to solve the + ** Eight Queens problem using a BASIC interpreter. He had + ** developed a program which placed eight queens successively + ** on all sixty-four squares, testing for conflicts at each + ** iteration. Of course, such a program would require 64^8 + ** iterations (about 2.8x10^14 iterations). Even in C on a, + ** fast CPU, this could take months or years. Byte's answer was + ** to alter the loops so that the queens resided on separate + ** ranks, thereby reducing the number of iterations required + ** to find all solutions to 8^8 iterations (about 16 million). + ** More reasonable, but still requiring a chunk of CPU time. + ** + ** I puzzled about this problem a bit, and came to realize that + ** this was still wasting a lot of CPU cycles. Though I'm sure + ** others have come up with good algorithms, I decided to come + ** up with my own, with a particular eye on efficiency. The + ** resulting algorithm finds all 8x8 solutions in a fraction + ** of a second (there are 92 solutions, including rotations). + ** On a Sun 4, it'll find all 365,596 solutions on a 14x14 board + ** in a bit over 2 minutes (printing them out requires extra + ** time, of course). Even Byte's solution would require 14^14 + ** iterations (about 10^16) which would take aeons. + ** + ** My algorithm works as follows: + ** (1) Place a queen in the top left corner. + ** (2) Place another queen immediately below. + ** (3) Test for conflicts. If the second queen conflicts (it + ** does at first), then move it one square to the right. + ** (4) Loop step 3 until there are no conflicts. Place + ** the next queen on the board and recurse. + ** (5) If any queen reaches the right edge of the board, + ** remove it and 'pop' to the previous recursion level. + ** (6) Now repeat these steps recursively until all eight + ** queens (or however many) have been placed without + ** conflict -- the result is a solution to the problem, + ** which is counted and optionally printed. + ** + ** Because conflicts are tested as the recursion proceeds, + ** this has the effect of 'pruning' the recursion so that + ** a large number of board positions are not even attempted. + ** The result is that the algorithm runs in reasonable time. + ** + ** I used a few tricks to make the test-for-conflict code + ** extremely efficient -- there is no 'inner' loop to search + ** along ranks, files, or diagonals. A series of arrays are + ** maintained instead which indicate which queen currently + ** 'owns' each rank, file or diagonal. This makes the + ** algorithm really fly, though the code is a little hard to + ** read. Lastly, pointer arithmetic is used to reduce the + ** number of implicit multiplications used in array addressing. + ** + ** + ** Contact: + ** For queries regarding this program, contact Roberto Sierra + ** at any of the following addresses: + ** + ** Roberto Sierra + ** bert at netcom.com (preferred address) + ** 73557.2101 at compuserve.com + ** + ** Tempered MicroDesigns + ** P.O. Box 170638 + ** San Francisco, CA 94117 + ** + ** + ** Fine Print: + ** This program is in the public domain and can be used for + ** any purpose whatsoever, including commercial application. + ** [I'd like to hear what you do with it, though.] + ** Absolutely no warranty or liability is implied or extended + ** by the author. + ** + ** + ** Modification History: + ** PRS 3/19/84 v1.0 -- Original version. + ** PRS 7/25/93 v1.1 -- ANSIfied the code. More efficient pointers. + */ + + + #include /* Need standard I/O functions */ + #include /* Need exit() routine interface */ + #include /* Need strcmp() interface */ + #ifdef MPW /* Macintosh MPW ONLY */ + # include /* Need cursor control interfaces */ + #endif + + #define MAXQUEENS 100 /* Max number of queens */ + #define MAXRANKS MAXQUEENS /* Max number of ranks (rows) */ + #define MAXFILES MAXQUEENS /* Max number of files (columns) */ + #define MAXDIAGS (MAXRANKS+MAXFILES-1) /* Max number of diagonals */ + #define EMPTY (MAXQUEENS+1) /* Marks unoccupied file or diagonal */ + + /* GLOBAL VARIABLES */ + + int queens; /* Number of queens to place */ + int ranks; /* Number of ranks (rows) */ + int files; /* Number of files (columns) */ + int printing = 1; /* TRUE if printing positions */ + int findall = 0; /* TRUE if finding all solutions */ + + unsigned long solutions = 0; /* Number of solutions found */ + int queen[MAXRANKS]; /* File on which each queen is located */ + int file[MAXFILES]; /* Which queen 'owns' each file */ + int fordiag[MAXDIAGS]; /* Which queen 'owns' forward diagonals */ + int bakdiag[MAXDIAGS]; /* Which queen 'owns' reverse diagonals */ + char *progname = NULL; /* The name of this program */ + + + /* -------------------------- PROTOTYPES ----------------------- */ + + void pboard(void); + void find(register int level); + + + /*-------------------------- main() ---------------------------- + ** MAIN program. The main purpose of this routine is to deal + ** with decoding the command line arguments, initializing the + ** various arrays, and starting the recursive search routine. + */ + void main(int argc, char **argv) + { + register int i; /* Loop variable */ + register char *p; /* Ptr to argument */ + char *usage = + "Usage: %s [-ac] n\n\ + \tn\tNumber of queens (rows and columns). An integer from 1 to 100.\n\ + \t-a\tFind and print all solutions.\n\ + \t-c\tCount all solutions, but do not print them.\n"; + + #ifdef MPW /* Macintosh MPW ONLY */ + InitCursorCtl(0); /* Enable cursor control */ + #endif + + progname = argv[0]; /* Name of the program */ + + /**** DECODE COMMAND LINE ARGUMENTS ****/ + printing = 0; + queens = 14; + findall = 1; + + for(i = 1; i < argc; ++i) { /* Scan through arguments */ + p = argv[i]; /* Ptr to base of argument */ + if(*p == '-') { /* Command line option? */ + while(*++p) { /* Loop through characters */ + switch(*p) { /* What is the character */ + case 'c': /* '-c' option */ + printing = 0; /* Counting, not printing */ + case 'a': /* '-a' option */ + findall = 1; /* Find all solutions */ + break; + default: /* Illegal option */ + fprintf(stderr,"%s: Illegal option '%s'\n",progname,argv[i]); + fprintf(stderr,usage,progname); + exit(-1); + } /* End of switch */ + } /* End of loop */ + } /* End of option test */ + else { + if(sscanf(p,"%d",&queens) != 1) { /* Read integer argument */ + fprintf(stderr,"%s: Non-integer argument '%s'\n",progname,p); + exit(-1); + } + if(queens <= 0) { /* N must be positive */ + fprintf(stderr,"%s: n must be positive integer\n",progname); + exit(-1); + } + if(queens > MAXQUEENS) { /* N can't be too large */ + fprintf(stderr,"%s: Can't have more than %d queens\n", + progname, MAXQUEENS); + exit(-1); + } + } /* End of argument test */ + } /* End of argument scan loop */ + if(!queens) { + fprintf(stderr,"%s: Missing n argument\n",progname); + fprintf(stderr,usage,progname); + exit(-1); + } + + ranks = files = queens; /* NxN board for N queens */ + printf("%d queen%s on a %dx%d board...\n", + queens, queens > 1 ? "s" : "", ranks, files); + fflush(stdout); + + /* Initialization */ + solutions = 0; /* No solutions yet */ + for(i = 0; i < MAXFILES; ++i) file[i] = EMPTY; + for(i = 0; i < MAXDIAGS; ++i) fordiag[i] = bakdiag[i] = EMPTY; + + /* Find all solutions (begin recursion) */ + find(0); + if(printing && solutions) putchar('\n'); + + /* Report results */ + if(solutions == 1) printf("...there is 1 solution\n"); + else printf("...there are %ld solutions\n", solutions); + + exit(0); /* No errors */ + } + + + /***********************/ + /**** ROUTINES ****/ + /***********************/ + + /*------------------------- pboard() --------------------------- + ** This routines prints the board for a particular solution. + ** The output is sent to stdout. + */ + void pboard(void) + { + register int i, j; /* Rank/File indices */ + + if(findall) /* Only if searching for all */ + printf("\nSolution #%lu:\n",solutions); /* Print solution number */ + + for(i = 0; i < ranks; ++i) { /* Loop through all ranks */ + for(j = 0; j < files; ++j) { /* Loop through all files */ + putchar(' '); /* Output a space */ + if(j == queen[i]) putchar('Q'); /* Output Q for queen... */ + else putchar('-'); /* or '-' if empty */ + } + putchar('\n'); /* Break line */ + } + fflush(stdout); /* Flush solution to output */ + } + + + /*-------------------------- find() ---------------------------- + ** FIND is the recursive heart of the program, and finds all + ** solutions given a set of level-1 fixed queen positions. + ** The routine moves a single queen through all files (columns) + ** at the current rank (recursion level). As the queen is moved, + ** conflict tests are made. If the queen can be placed without + ** conflict, then the routine recurses to the next level. When + ** all queens have been placed without conflict, a solution is + ** counted and reported. + */ + void find(register int level) + { + register int f; /* Indexes through files */ + register int *fp, *fdp, *bdp; /* Ptrs to file/diagonal entries */ + + #ifdef MPW /* Macintosh MPW ONLY */ + if(level & 7 == 0) /* Periodically break for... */ + SpinCursor(1); /* background processing */ + #endif + + if(level == queens) { /* Placed all queens? Stop. */ + ++solutions; /* This is a solution! */ + if(printing) pboard(); /* Print board if printing */ + if(!findall) exit(0); /* May stop after first solution */ + #ifdef MPW /* Macintosh MPW ONLY */ + SpinCursor(1); /* background processing */ + #endif + } + else { /* Not at final level yet */ + for( /* Move queen through all files */ + f = 0, /* Queen starts at left (file 0) */ + fp = file, /* Ptr to base of file array */ + fdp = &fordiag[level], /* Ptr to first fwd diag entry */ + bdp = &bakdiag[level+files-1] /* Ptr to first bak diag entry */ + ; + f < files /* Loop through all files */ + ; + ++f, /* Advance index */ + ++fp, ++fdp, --bdp /* Advance pointers */ + ) { + if(*fp >= level && /* No queen on the file? */ + *fdp >= level && *bdp >= level /* No queens on diagonals? */ + ) { + queen[level] = f; /* Note new position of queen */ + *fp = *fdp = *bdp = level; /* Place queen on file & diags */ + find(level+1); /* This level OK, recurse to next */ + *fp = *fdp = *bdp = EMPTY; /* Remove queen from file & diags */ + } /* End of conflict test */ + } /* End of file loop */ + } /* End if (level == queens) */ + } + + From lattner at cs.uiuc.edu Tue Oct 5 15:59:15 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 15:59:15 -0500 Subject: [llvm-commits] CVS: llvm-test/SingleSource/Benchmarks/Misc/queens.c Message-ID: <200410052059.PAA26746@apoc.cs.uiuc.edu> Changes in directory llvm-test/SingleSource/Benchmarks/Misc: queens.c (r1.1) removed --- Log message: Move this to the McGill directory --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 16:05:21 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 16:05:21 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/football/ Message-ID: <200410052105.QAA27079@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/football: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/football added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 16:05:48 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 16:05:48 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/football/Makefile common.c common.h definitions.h io.c io.h sort.c sort.h stats stats.c stats.h Message-ID: <200410052105.QAA27114@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/football: Makefile added (r1.1) common.c added (r1.1) common.h added (r1.1) definitions.h added (r1.1) io.c added (r1.1) io.h added (r1.1) sort.c added (r1.1) sort.h added (r1.1) stats added (r1.1) stats.c added (r1.1) stats.h added (r1.1) --- Log message: New program --- Diffs of the changes: (+2266 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/football/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/football/Makefile:1.1 *** /dev/null Tue Oct 5 16:05:47 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/football/Makefile Tue Oct 5 16:05:36 2004 *************** *** 0 **** --- 1,5 ---- + LEVEL = ../../../.. + + PROG = football + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/football/common.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/football/common.c:1.1 *** /dev/null Tue Oct 5 16:05:47 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/football/common.c Tue Oct 5 16:05:36 2004 *************** *** 0 **** --- 1,388 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + #include + #include "definitions.h" + #include "stats.h" + + TEAMS_STATS common_games; + TEAM common_teams[NUM_TEAMS+1]; + + extern void display_split(FILE *stream,TEAM *teams,int split,int num); + + BOOL matches_any_team(int num,TEAM code) + { + int i; + for (i=1;i<=num;i++) + if (common_teams[i] == code) + return i; + return NO; + } + + void common(int num) + { + TEAM tmp_team,temp; + int week,game,i; + int in_common[NUM_TEAMS+1]; + TEAM team1,team2; + int site1,site2; + + for (tmp_team=1;tmp_team<=NUM_TEAMS; tmp_team++) + in_common[tmp_team] = 0; + + for (temp=1;temp<=num;temp++) + for (tmp_team=1;tmp_team<=NUM_TEAMS; tmp_team++) + in_common[tmp_team] += team_plays[common_teams[temp]][tmp_team]; + + for (temp=1;temp<=NUM_TEAMS;temp++) { + if (in_common[temp] < num) + in_common[temp] = NO; + else in_common[temp] = YES; + } + /* stats */ + for (team1=1;team1<=NUM_TEAMS; team1++) { + common_games[team1].wins = common_games[team1].loses = 0; + common_games[team1].ties = 0; + common_games[team1].points_for = common_games[team1].points_against = 0; + } + + for (week = 1; week <= num_games;week++) + for (game = 1;game<=NUM_TEAMS/2; game++) + for (i = 1; i<=2; i++) { + if ( i == 1) { + team1 = sched[week][game][HOST]; site1 = HOST; + team2 = sched[week][game][VISITOR]; site2 = VISITOR; + } else { + team1 = sched[week][game][VISITOR]; site1 = VISITOR; + team2 = sched[week][game][HOST]; site2 = HOST; + } + if ( team1 != 0 && in_common[team1] ) + if (matches_any_team(num,team2)) + if (scores[week][game][HOST] >= 0 && + scores[week][game][VISITOR] >=0) { + if (scores[week][game][site1] < scores[week][game][site2]) + common_games[team2].wins ++; + else if (scores[week][game][site1] > scores[week][game][site2]) + common_games[team2].loses ++; + else common_games[team2].ties ++; + } else common_games[team2].points_for ++; + } + for (team1=1;team1<=28;team1++) + if (common_games[team1].wins + common_games[team1].loses + + common_games[team1].ties + common_games[team1].points_for < 4) + common_games[team1].wins = -1; + } + + + int head_to_head_sweap(TEAM *teams,int num) + { + TEAM temp1,temp2; + BOOL sweap_win=YES,sweap_lose=YES; + + for (temp1=0;temp1 MAX_TEAMS_DIV) { + (void) printf("ERROR in head_to_head (common.c). Assumption violated.\n"); + exit(1); + } + + best_pct = 0.0; + num_best = 0; + for (i=0;i best_pct) { + best_pct = pct[i]; + num_best = 0; + } + if (pct[i] == best_pct) num_best++; + } + + split_around(teams,num_best,num,pct,best_pct); + return num_best; + } + + + /* */ + int break_common(TEAM *teams,int num) + { + int i; + double best_pct,pct[NUM_TEAMS]; + int num_best; + + if (num > NUM_TEAMS) { + (void) printf("ERROR in break_common (common.c). Assumption violated.\n"); + exit(1); + } + + for (i=0;i best_pct) { + best_pct = pct[i]; + num_best = 0; + } + if (pct[i] == best_pct) num_best++; + } + + split_around(teams,num_best,num,pct,best_pct); + return num_best; + } + + /* */ + int div_conf_rec(TEAM *teams,int num,int which) + { + int i; + double best_pct,pct[NUM_TEAMS]; + int num_best; + + if (num > NUM_TEAMS) { + (void) printf("ERROR in div_conf_rec (common.c). Assumption violated.\n"); + exit(1); + } + + best_pct = 0.0; + num_best = 0; + for (i=0;i best_pct) { + best_pct = pct[i]; + num_best = 0; + } + if (pct[i] == best_pct) num_best++; + } + + split_around(teams,num_best,num,pct,best_pct); + return num_best; + } + + int break_net_points(TEAM *teams,int num,int which) + { + int i; + double best_pct,pct[NUM_TEAMS]; + int num_best; + + if (num > NUM_TEAMS) { + (void) printf("ERROR in break_net_points (common.c). Assumption violated.\n"); + exit(1); + } + + best_pct = -10000.0; + num_best = 0; + for (i=0;i best_pct) { + best_pct = pct[i]; + num_best = 0; + } + if (pct[i] == best_pct) num_best++; + } + + split_around(teams,num_best,num,pct,best_pct); + return num_best; + } + + void break_a_tie(TEAM *teams,int num,BOOL display) + { + BOOL ALL_SAME_DIV; + int value,i; + + if (num <= 1) return; + + ALL_SAME_DIV = YES; + for (i=1;i= 1.0 ? "1" : " ") + #define DISP2_PCT(X) (WIN_PCT(X) >= 1.0 ? 0 : (int) (WIN_PCT(X)*1000+.5)) + + #define DISP_REC_HEADER(output) (void) fprintf(output," W L T Pct. PF PA") + #define DISP_RECORD(output,teamcode) (void) fprintf(output, \ + "%- 14s%1s %2d %2d %2d %s.%03d %3d %3d", \ + team[teamcode][FULL_NAME_0], \ + (a_champ(teamcode) ? "*" : \ + (a_wild_card(teamcode) ? "+" : " ")), \ + team_info[teamcode].wins,team_info[teamcode].loses, \ + team_info[teamcode].ties, \ + DISP1_PCT(team_info[teamcode]), \ + DISP2_PCT(team_info[teamcode]), \ + team_info[teamcode].points_for, \ + team_info[teamcode].points_against) + + #define PER_GAME(info,N,T) ((info[T].wins + info[T].loses + info[T].ties) == 0 ? 0.0 : ((double) N / (info[T].wins + info[T].loses + info[T].ties))) + + #define NET_POINTS(info,A) (info[A].points_for-info[A].points_against) + + #define sort(A,lt,lower,upper,O) {int i,j; BOOL flag; int temp;\ + flag = YES; for (i=lower; i<=upper && flag; i ++) {flag = NO;\ + for (j=upper; j>i; j --) \ + if (lt(A,O[j],O[j-1])) { \ + temp = O[j-1]; O[j-1]=O[j]; O[j]=temp; flag = YES;}}} Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/football/io.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/football/io.c:1.1 *** /dev/null Tue Oct 5 16:05:47 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/football/io.c Tue Oct 5 16:05:36 2004 *************** *** 0 **** --- 1,1041 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + #include + #include + #include "definitions.h" + #include "stats.h" + #include "sort.h" + #include "common.h" + + #define MAX_RESP_LEN 50 + char responce[MAX_RESP_LEN+1]; + BOOL got_unused_responce = NO; + + extern char *strcat(char *s1, const char *s2); + extern int strncmp(const char *s1, const char *s2, size_t n); + + void prompt(FILE *output,FILE *input) + { + extern char *get_responce(FILE *input); + char *str; + + (void) fprintf(output,"Hit return to continue: "); + str = get_responce(input); + if (*str != '\0') + got_unused_responce = YES; + } + + #define find_conf_rank(r,t) (divisions[t][CONFERENCE] == NFC_0 ? \ + find_teams_rank(r,t) : \ + find_teams_rank(r,t) - NUM_TEAMS/2) + + int str_to_int(char *s) + { + int value; + char *temp; + + value=0; + for (temp=s; *temp != '\0'; temp++) + {value = value*10 + (( (*temp >= '0') && (*temp <= '9') ) ? + (*temp) - '0' : 0); + } + return value; + } + + int find_teams_rank(ORDERING rank,int team_code) + { + int i; + + for (i=1;i<=NUM_TEAMS;i++) + if (rank[i]==team_code) return i; + return 0; + } + + int white_space(char A) + { + static int commentP=0; + if (A == '%') {commentP = YES; return 1;} + if (commentP) { + if (A == '\n') commentP = 0; + return 1; + } + + if (A == ' ' || A == '\n' || A == '\t') + return 1; + else return 0; + } + + void clear_screen(FILE *output) + { + (void) fprintf(output,"\n\n=========================================\n"); + } + + void lower_case(char *str) + { + for (;*str != '\0';str++) + if ( 'A' <= *str && *str <= 'Z') + *str = *str + ('a' - 'A'); + } + + char *skip_white_space(char *str) + { + for (;white_space(*str) && *str != '\0'; str ++); + return str; + } + BOOL end_of_line(char *str) + { + return *str == '\0'; + } + + TEAM find_next_name(FILE *output,char *str) + { + char *last,last_ch; + TEAM value; + + str = skip_white_space(str); + for (last = str; !white_space(*last); last++) {} + last_ch = *last; + *last = '\0'; + value = find_name(output,str); + *last = last_ch; + return value; + } + + BOOL matches(char *str1,char *comm, int min_len_for_match) + { + int length; + + for (length=0;!white_space(*(str1+length)) && *(str1+length) != '\0'; + length ++); + + if (length < min_len_for_match) + return NO; + else + if (length > strlen(comm)) + return (!strncmp(str1,comm,strlen(comm))) && white_space(*(str1+strlen(comm))); + else + return (!strncmp(str1,comm,length)); + } + + char *skip_first(char *str) + { + for (;!white_space(*str) && *str != '\0'; str ++); + for (;white_space(*str) && *str != '\0'; str ++); + return (str); + } + + char *get_responce(FILE *input) + { + char *resp; + extern int in_fileP; + + if (!got_unused_responce) { + (void) fgets(responce,MAX_RESP_LEN,input); + if (in_fileP) (void) fprintf(stdout,"%s\n",responce); + + lower_case(responce); + + for (resp=responce+strlen(responce)-1; + resp >= responce && white_space(*resp); + resp --) + *resp = '\0'; + } + else got_unused_responce = NO; + + for (resp=responce; *resp != '\0' && white_space(*resp); resp++); + return(resp); + } + + int find_nth_place_team(ORDERING standings,int conf,int div,int place) + { + int team_code; + int next_found_is; + + next_found_is = 1; + + for (team_code=1; team_code <= NUM_TEAMS; team_code ++) + if ((divisions[standings[team_code]][CONFERENCE] == conf || + conf == WILD_CARD) && + (divisions[standings[team_code]][DIVISION] == div || + div == WILD_CARD)) + if (next_found_is == place) return standings[team_code]; + else next_found_is ++; + return 0; + } + + #define PRINT_RESULT(week) \ + if (week > num_games) (void) fprintf(output, \ + " "); \ + else { int i,score,opp_score; \ + for (i=1;sched[week][i][HOST] != team_code && \ + sched[week][i][VISITOR] != team_code && i <= NUM_TEAMS/2; i++) ; \ + if (i == NUM_TEAMS/2+1) \ + (void) fprintf(output," "); \ + else {if (sched[week][i][VISITOR] == team_code) {\ + (void) fprintf(output,"at %-15s ", \ + team[sched[week][i][HOST]][FULL_NAME_0]); \ + score = scores[week][i][VISITOR]; \ + opp_score = scores[week][i][HOST]; } \ + else {(void) fprintf(output,"%-15s ", \ + team[sched[week][i][VISITOR]][FULL_NAME_0]); \ + score = scores[week][i][HOST]; \ + opp_score = scores[week][i][VISITOR]; } \ + if (score == -1 || opp_score == -1 ) \ + (void) fprintf(output," "); \ + else {if (score == opp_score) \ + (void) fprintf(output,"T"); \ + else if (score > opp_score) \ + (void) fprintf(output,"W"); \ + else (void) fprintf(output,"L"); \ + (void) fprintf(output,"%2d-%2d ",score,opp_score);} \ + }} + + void display_info(FILE *output,int team_code) + { + int week; + int tmp_team; + + clear_screen(output); + + (void) fprintf(output,"%s team information.\n\n", + team[team_code][FULL_NAME_0]); + + for (week=1;week <= 21; week ++) { + PRINT_RESULT(week); + switch (week) { + case 1: + (void) fprintf(output,"%s %s",CONF_STR(team_code), + DIVISION_STR(team_code)); + break; + case 2: + DISP_REC_HEADER(output); break; + case 3: case 4: case 5: case 6: case 7: + if (tmp_team = find_nth_place_team(standings, + divisions[team_code][CONFERENCE], + divisions[team_code][DIVISION], + week-2)) + DISP_RECORD(output,tmp_team); + break; + case 9: + (void) fprintf(output,"Record %2d-%d-%d %sRank %d/%d", + team_info[team_code].wins, + team_info[team_code].loses,team_info[team_code].ties, + (team_info[team_code].wins < 10 && + team_info[team_code].loses < 10 ? " " : " "), + find_conf_rank(conf_standings,team_code), + find_teams_rank(abs_standings,team_code)); + break; + case 10: + (void) fprintf(output,"Points scored %3d [%6.1f] Rank %d/%d", + team_info[team_code].points_for, + PER_GAME(team_info,team_info[team_code].points_for, + team_code), + find_conf_rank(offence_ranks,team_code), + find_teams_rank(offence_ranks_nfl,team_code)); + break; + case 11: + (void) fprintf(output,"Points allowed %3d [%6.1f] Rank %d/%d", + team_info[team_code].points_against, + PER_GAME(team_info,team_info[team_code].points_against, + team_code), + find_conf_rank(defence_ranks,team_code), + find_teams_rank(defence_ranks_nfl,team_code)); + break; + case 12: + (void) fprintf(output,"Net Points %4d [%6.1f] Rank %d/%d", + NET_POINTS(team_info,team_code), + PER_GAME(team_info,NET_POINTS(team_info,team_code), + team_code), + find_conf_rank(net_ranks,team_code), + find_teams_rank(net_ranks_nfl,team_code)); + break; + case 14: + (void) fprintf(output,"Major Tie-breakers:"); break; + case 15: + (void) fprintf(output,"-(1/1) Head to Head"); break; + case 16: + (void) fprintf(output,"-(2/ ) Divisional Record %d-%d-%d", + team_info_wi_div[team_code].wins, + team_info_wi_div[team_code].loses, + team_info_wi_div[team_code].ties); + break; + case 17: + (void) fprintf(output,"-(3/2) Conference Record %d-%d-%d", + team_info_wi_conf[team_code].wins, + team_info_wi_conf[team_code].loses, + team_info_wi_conf[team_code].ties); + break; + case 18: + (void) fprintf(output,"-(4/3) Common Games"); break; + case 19: + (void) fprintf(output,"-(5/ ) Net points in %s %s %d [%3.1f]", + CONF_STR(team_code),DIVISION_STR(team_code), + NET_POINTS(team_info_wi_div,team_code), + PER_GAME(team_info_wi_div, + NET_POINTS(team_info_wi_div,team_code), + team_code)); + break; + case 20: + (void) fprintf(output,"-( /4) Avg. net points in %s %3.1f", + CONF_STR(team_code), + PER_GAME(team_info_wi_conf, + NET_POINTS(team_info_wi_conf,team_code), + team_code)); + break; + case 21: + (void) fprintf(output,"-(6/5) Total net points %d [%3.1f]", + NET_POINTS(team_info,team_code), + PER_GAME(team_info,NET_POINTS(team_info,team_code), + team_code)); + break; + default: + break; + } + + (void) fprintf(output,"\n"); + } + } + + BOOL is_any(TEAM *teams,int num,TEAM code) + { + int i; + for (i=0;i\n"); + (void) fprintf(output,"Enter week with-prompts\n"); + (void) fprintf(output,"Display all-ranks\n"); + (void) fprintf(output,"Display defensive-rank\n"); + (void) fprintf(output,"Display information-about \n"); + (void) fprintf(output,"Display menu\n"); + (void) fprintf(output,"Display offensive-rank\n"); + (void) fprintf(output,"Display net-rank\n"); + (void) fprintf(output,"Display records\n"); + (void) fprintf(output,"Display standings\n"); + (void) fprintf(output,"Display team-names/abbr\n"); + (void) fprintf(output,"Display tie-breaker-information-for \n"); + (void) fprintf(output,"Display week \n"); + (void) fprintf(output,"How-ties-broken conference\n"); + (void) fprintf(output,"How-ties-broken division\n"); + (void) fprintf(output,"Quit\n"); + (void) fprintf(output,"Save\n"); + if (!current_with_disk) + (void) fprintf(output,"[WARNING: Database is not current with disk.]\n"); + } + + while (!valid_input) { + if (!got_unused_responce) + (void) fprintf(output,"\n Enter option: "); + + resp = get_responce(input); + + if (matches(resp,"quit",1) || feof(input)) { + (void) fprintf(output,"\n"); + terminate = YES; + valid_input = YES; + } + if (matches(resp,"how-ties-broken",1)) { + resp = skip_first(resp); + if (matches(resp,"division",1)) { + (void) fprintf(output,"\n"); + valid_input = YES; + break_ties(team_info,standings,DIVISION,YES); + } else if (matches(resp,"conference",1)) { + (void) fprintf(output,"\n"); + valid_input = YES; + break_ties(team_info,conf_standings,CONFERENCE,YES); + } + } else + if (matches(resp,"display",1)) { + + resp = skip_first(resp); + if (matches(resp,"menu",1)) + valid_input = YES; + else if (matches(resp,"standings",1)) { + valid_input = YES; + display_standings(output); + prompt(output,input); + } + else if (matches(resp,"information-about",1)) { + int team_code; + + resp = skip_first(resp); + if ((team_code = find_name(output,resp))) { + valid_input = YES; + display_info(output,team_code); + prompt(output,input); + } + } + else if (matches(resp,"tie-breaker-information-for",2)) { + TEAM code,team_code[NUM_TEAMS]; + int num,i; + num = 0; + resp = skip_first(resp); + resp = skip_white_space(resp); + while (*resp != '\0') + if ((code = find_next_name(output,resp))) { + BOOL temp; + temp = YES; + for (i=0;i + #include "definitions.h" + #include "stats.h" + #include "common.h" + #include "io.h" + + BOOL absolute_standing_lt(TEAMS_STATS info,int team1,int team2) + { + if (WIN_PCT(info[team1]) != WIN_PCT(info[team2])) + return (WIN_PCT(info[team1]) > WIN_PCT(info[team2])); + + if (info[team1].loses == 0 && info[team2].loses == 0) + return (info[team1].wins > info[team2].wins); + + if (info[team1].wins == 0 && info[team2].wins == 0) + return (info[team1].loses < info[team2].loses); + + if (a_champ(team1) != a_champ(team2)) + return a_champ(team1); + if (a_wild_card(team1) != a_wild_card(team2)) + return a_wild_card(team1); + if (divisions[team1][CONFERENCE] != divisions[team2][CONFERENCE]) + return( divisions[team1][CONFERENCE] < divisions[team2][CONFERENCE] ); + return(team1 < team2); + } + + BOOL standing_lt(TEAMS_STATS info,int team1,int team2) + { + if (divisions[team1][CONFERENCE] != divisions[team2][CONFERENCE]) + return( divisions[team1][CONFERENCE] < divisions[team2][CONFERENCE] ); + + if (divisions[team1][DIVISION] != divisions[team2][DIVISION]) + return( divisions[team1][DIVISION] < divisions[team2][DIVISION] ); + + return absolute_standing_lt(info,team1,team2); + } + + BOOL conf_standing_lt(TEAMS_STATS info,int team1,int team2) + { + if (divisions[team1][CONFERENCE] != divisions[team2][CONFERENCE]) + return( divisions[team1][CONFERENCE] < divisions[team2][CONFERENCE] ); + + return absolute_standing_lt(info,team1,team2); + } + + BOOL defence_lt(TEAMS_STATS info,int team1,int team2) + { + if (divisions[team1][CONFERENCE] != divisions[team2][CONFERENCE]) + return( divisions[team1][CONFERENCE] < divisions[team2][CONFERENCE] ); + + if (PER_GAME(info,info[team1].points_against,team1) != + PER_GAME(info,info[team2].points_against,team2)) + return (PER_GAME(info,info[team1].points_against,team1) < + PER_GAME(info,info[team2].points_against,team2)); + + return (team1 < team2); + } + + BOOL defence_nfl_lt(TEAMS_STATS info,int team1,int team2) + { + if (PER_GAME(info,info[team1].points_against,team1) != + PER_GAME(info,info[team2].points_against,team2)) + return (PER_GAME(info,info[team1].points_against,team1) < + PER_GAME(info,info[team2].points_against,team2)); + + return (team1 < team2); + } + + BOOL offence_lt(TEAMS_STATS info,int team1,int team2) + { + if (divisions[team1][CONFERENCE] != divisions[team2][CONFERENCE]) + return( divisions[team1][CONFERENCE] < divisions[team2][CONFERENCE] ); + + if (PER_GAME(info,info[team1].points_for,team1) != + PER_GAME(info,info[team2].points_for,team2)) + return (PER_GAME(info,info[team1].points_for,team1) > + PER_GAME(info,info[team2].points_for,team2)); + + return (team1 < team2); + } + + BOOL offence_nfl_lt(TEAMS_STATS info,int team1,int team2) + { + if (PER_GAME(info,info[team1].points_for,team1) != + PER_GAME(info,info[team2].points_for,team2)) + return (PER_GAME(info,info[team1].points_for,team1) > + PER_GAME(info,info[team2].points_for,team2)); + + return (team1 < team2); + } + + + BOOL net_nfl_lt(TEAMS_STATS info,int team1,int team2) + { + if (PER_GAME(info,NET_POINTS(info,team1),team1) != + PER_GAME(info,NET_POINTS(info,team2),team2)) + return (PER_GAME(info,NET_POINTS(info,team1),team1) > + PER_GAME(info,NET_POINTS(info,team2),team2)); + + return (team1 < team2); + } + + BOOL net_lt(TEAMS_STATS info,int team1,int team2) + { + if (divisions[team1][CONFERENCE] != divisions[team2][CONFERENCE]) + return( divisions[team1][CONFERENCE] < divisions[team2][CONFERENCE] ); + + return net_nfl_lt(info,team1,team2); + } + + BOOL tied(TEAMS_STATS info,int team1,int team2) + { + if (WIN_PCT(info[team1]) != WIN_PCT(info[team2])) + return NO; + + if (info[team1].loses == 0 && info[team2].loses == 0) + return (info[team1].wins == info[team2].wins); + + if (info[team1].wins == 0 && info[team2].wins == 0) + return (info[team1].loses == info[team2].loses); + + return YES; + } + + + #define CHAMP(champ,conf,div) if ( (champ == ERROR_0) && \ + (divisions[rank[team_c]][CONFERENCE] == conf) && \ + (divisions[rank[team_c]][DIVISION] == div) ) \ + champ = rank[team_c] + + + void break_ties(TEAMS_STATS info,ORDERING rank,int within,BOOL display) + { + int i,first_of_equals; + int team_c; + int afc,nfc; + + if (within == DIVISION && !display) { + nfc_east_champ = nfc_central_champ = nfc_west_champ = ERROR_0; + afc_east_champ = afc_central_champ = afc_west_champ = ERROR_0; + } + if (within != NFL_0 && !display) { + nfc_wild_card1 = nfc_wild_card2 = nfc_wild_card3 = ERROR_0; + afc_wild_card1 = afc_wild_card2 = afc_wild_card3 = ERROR_0; + } + first_of_equals = 1; + for (i=1; i <= NUM_TEAMS; i ++) + if ( !((i == NUM_TEAMS) ? NO : + (tied(info,rank[i],rank[i+1]) ? + (within == DIVISION ? + (divisions[rank[i]][DIVISION] == divisions[rank[i+1]][DIVISION] && + divisions[rank[i]][CONFERENCE]==divisions[rank[i+1]][CONFERENCE]) + :(within == CONFERENCE ? + (divisions[rank[i]][CONFERENCE]==divisions[rank[i+1]][CONFERENCE] + && (a_champ(rank[i]) == a_champ(rank[i+1]))) + : (a_champ(rank[i]) == a_champ(rank[i+1])) && + (a_wild_card(rank[i]) == a_wild_card(rank[i+1])) + )) : NO)) ) { + if ( i != first_of_equals) { + break_a_tie(&(rank[first_of_equals]),i-first_of_equals+1,display); + if (display) { + extern BOOL got_unused_responce; + + prompt(stdout,stdin); + if (got_unused_responce) display = NO; + } + } + first_of_equals = i+1; + } + + afc = nfc = 0; + if (within == DIVISION) + for (team_c=1; team_c <= NUM_TEAMS; team_c ++) { + CHAMP(nfc_east_champ,NFC_0,EAST_0); + CHAMP(nfc_central_champ,NFC_0,CENTRAL_0); + CHAMP(nfc_west_champ,NFC_0,WEST_0); + CHAMP(afc_east_champ,AFC_0,EAST_0); + CHAMP(afc_central_champ,AFC_0,CENTRAL_0); + CHAMP(afc_west_champ,AFC_0,WEST_0); + } else if (within == CONFERENCE) + for (team_c=1; team_c <= NUM_TEAMS; team_c ++) { + if (divisions[conf_standings[team_c]][CONFERENCE] == NFC_0) { + if (!(a_champ(conf_standings[team_c]))) + if (nfc == 0) {nfc++; nfc_wild_card1 = conf_standings[team_c];} + else if (nfc == 1) {nfc++; nfc_wild_card2 = conf_standings[team_c];} + else if (nfc == 2 && (iyear >= 90 || iyear <=70)) + {nfc++; nfc_wild_card3 = conf_standings[team_c];} + } else { + if (!(a_champ(conf_standings[team_c]))) + if (afc == 0) {afc++; afc_wild_card1 = conf_standings[team_c];} + else if (afc == 1) {afc++; afc_wild_card2 = conf_standings[team_c];} + else if (afc == 2 && (iyear >= 90 || iyear <= 70)) + {afc++; afc_wild_card3 = conf_standings[team_c];} + } + } + } + + void sort_all(void) + { + sort(team_info,standing_lt,1,NUM_TEAMS,standings); + break_ties(team_info,standings,DIVISION,NO); + sort(team_info,conf_standing_lt,1,NUM_TEAMS,conf_standings); + break_ties(team_info,conf_standings,CONFERENCE,NO); + sort(team_info,absolute_standing_lt,1,NUM_TEAMS,abs_standings); + break_ties(team_info,abs_standings,NFL_0,NO); + sort(team_info,defence_lt,1,NUM_TEAMS,defence_ranks); + sort(team_info,defence_nfl_lt,1,NUM_TEAMS,defence_ranks_nfl); + sort(team_info,offence_lt,1,NUM_TEAMS,offence_ranks); + sort(team_info,offence_nfl_lt,1,NUM_TEAMS,offence_ranks_nfl); + sort(team_info,net_lt,1,NUM_TEAMS,net_ranks); + sort(team_info,net_nfl_lt,1,NUM_TEAMS,net_ranks_nfl); + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/football/sort.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/football/sort.h:1.1 *** /dev/null Tue Oct 5 16:05:47 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/football/sort.h Tue Oct 5 16:05:36 2004 *************** *** 0 **** --- 1,5 ---- + extern BOOL standing_lt(TEAMS_STATS info,int team1,int team2); + extern BOOL defence_lt(TEAMS_STATS info,int team1,int team2); + extern BOOL defence_nfl_lt(TEAMS_STATS info,int team1,int team2); + extern void sort_all(void); + extern void break_ties(TEAMS_STATS info,ORDERING rank,int within,BOOL display); Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/football/stats Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/football/stats.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/football/stats.c:1.1 *** /dev/null Tue Oct 5 16:05:48 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/football/stats.c Tue Oct 5 16:05:37 2004 *************** *** 0 **** --- 1,488 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + #include + #include + #include + #include "definitions.h" + #include "io.h" + #include "sort.h" + + #define MAX_FILE_NAME_LEN 100 + + extern char *strcat(char *s1, const char *s2); + + BOOL preseason = NO; + int num_games; + + BOOL terminate = NO; + + FILE *schedule; + #define SCHED_0 "data/sched.19" + char inp_sched[MAX_FILE_NAME_LEN+1]; + + FILE *the_scores; + #define SCORE_0 "data/scores.19" + char input_score[MAX_FILE_NAME_LEN+1]; + + SCHED_TYPE sched; + SCORES_TYPE scores; + TEAMS_STATS team_info,team_info_wi_conf,team_info_wi_div; + BOOL team_plays[NUM_TEAMS+1][NUM_TEAMS+1]; + H_TO_H_STATS h_to_h_stats; + + BOOL current_with_disk; + + TEAM_TYPE team= {{"error"," "}, + {"min","Minnesota"}, + {"atl","Atlanta"}, + {"chi","Chicago"}, + {"dal","Dallas"}, + {"det","Detroit"}, + {"gb","Green Bay"}, + {"ram","L.A. Rams"}, + {"no","New Orleans"}, + {"gia","N.Y. Giants"}, + {"phi","Philadelphia"}, + {"pho","Phoenix"}, + {"sf","San Francisco"}, + {"tb","Tampa Bay"}, + {"was","Washington"}, + {"buf","Buffalo"}, + {"cin","Cincinnati"}, + {"cle","Cleveland"}, + {"den","Denver"}, + {"hou","Houston"}, + {"ind","Indianapolis"}, + {"kc","Kansas City"}, + {"rai","L.A. Raiders"}, + {"mia","Miami"}, + {"ne","New England"}, + {"jet","N.Y. Jets"}, + {"pit","Pittsburgh"}, + {"sd","San Diego"}, + {"sea","Seattle"}, + {"none","None"}}; + + DIVISION_TYPE divisions = {{0,0}, {NFC_0,CENTRAL_0}, {NFC_0,WEST_0}, + {NFC_0,CENTRAL_0}, {NFC_0,EAST_0}, {NFC_0,CENTRAL_0}, + {NFC_0,CENTRAL_0}, {NFC_0,WEST_0}, {NFC_0,WEST_0}, + {NFC_0,EAST_0}, {NFC_0,EAST_0}, {NFC_0,EAST_0}, + {NFC_0,WEST_0}, {NFC_0,CENTRAL_0}, {NFC_0,EAST_0}, + {AFC_0,EAST_0}, {AFC_0,CENTRAL_0}, {AFC_0,CENTRAL_0}, + {AFC_0,WEST_0}, {AFC_0,CENTRAL_0}, {AFC_0,EAST_0}, + {AFC_0,WEST_0}, {AFC_0,WEST_0}, {AFC_0,EAST_0}, + {AFC_0,EAST_0}, {AFC_0,EAST_0}, {AFC_0,CENTRAL_0}, + {AFC_0,WEST_0}, {AFC_0,WEST_0}}; + + ORDERING standings,conf_standings,abs_standings; + ORDERING defence_ranks,defence_ranks_nfl; + ORDERING offence_ranks,offence_ranks_nfl; + ORDERING net_ranks,net_ranks_nfl; + + TEAM nfc_east_champ, nfc_central_champ, nfc_west_champ; + TEAM afc_east_champ, afc_central_champ, afc_west_champ; + TEAM nfc_wild_card1, nfc_wild_card2,nfc_wild_card3; + TEAM afc_wild_card1, afc_wild_card2,afc_wild_card3; + + int iyear; + + BOOL a_wild_card(TEAM team) + { + return (team == nfc_wild_card1 || team == nfc_wild_card2 || + team == nfc_wild_card3 || team == afc_wild_card1 || + team == afc_wild_card2 || team == afc_wild_card3); + } + + BOOL a_champ(TEAM team) + { + return (team == nfc_east_champ || team == nfc_central_champ || + team == nfc_west_champ || team == afc_east_champ || + team == afc_central_champ || team == afc_west_champ); + } + + int find_name(FILE *output,char name[]) + { + int i; + char full_name[MAX_NAME_LENGTH]; + + for (i = 1;i<=NUM_TEAMS+1;i++) { + (void) strcpy(full_name,team[i][FULL_NAME_0]); + lower_case(full_name); + if (! strcmp(team[i][ABBR_0],name) || !strcmp(full_name,name)) + return i; + } + (void) fprintf(output,"No such team %s\n",name); + return 0; + } + + void compute_team_info(void) + { + int week,game,team,i; + + for (team=1;team<=NUM_TEAMS; team++) + for (i=1;i<=NUM_TEAMS;i++) + team_plays[team][i] = 0; + + for (team=1;team<=NUM_TEAMS; team++) { + team_info[team].wins = team_info[team].loses = team_info[team].ties = 0; + team_info[team].points_for = team_info[team].points_against = 0; + + team_info_wi_conf[team].wins = 0; + team_info_wi_conf[team].loses = 0; + team_info_wi_conf[team].ties = 0; + team_info_wi_conf[team].points_for = 0; + team_info_wi_conf[team].points_against = 0; + + team_info_wi_div[team].wins = 0; + team_info_wi_div[team].loses = 0; + team_info_wi_div[team].ties = 0; + team_info_wi_div[team].points_for = 0; + team_info_wi_div[team].points_against = 0; + + for (i=1;i<=NUM_TEAMS; i++) { + h_to_h_stats[team][i].wins = h_to_h_stats[team][i].loses = + h_to_h_stats[team][i].ties = h_to_h_stats[team][i].points_for = + h_to_h_stats[team][i].points_against = 0; + } + } + + for (week=1;week<=num_games; week++) + for (game=1;game<=NUM_TEAMS/2; game++) { + team_plays[sched[week][game][HOST]][sched[week][game][VISITOR]] = YES; + team_plays[sched[week][game][VISITOR]][sched[week][game][HOST]] = YES; + if (scores[week][game][HOST] >= 0 && scores[week][game][VISITOR] >=0) { + + h_to_h_stats[sched[week][game][HOST]] + [sched[week][game][VISITOR]].points_for += scores[week][game][HOST]; + h_to_h_stats[sched[week][game][HOST]] + [sched[week][game][VISITOR]].points_against += + scores[week][game][VISITOR]; + h_to_h_stats[sched[week][game][VISITOR]] + [sched[week][game][HOST]].points_for += scores[week][game][VISITOR]; + h_to_h_stats[sched[week][game][VISITOR]] + [sched[week][game][HOST]].points_against += + scores[week][game][HOST]; + + if (scores[week][game][HOST] < scores[week][game][VISITOR]) { + team_info[sched[week][game][HOST]].loses ++; + team_info[sched[week][game][VISITOR]].wins ++; + + h_to_h_stats[sched[week][game][HOST]] + [sched[week][game][VISITOR]].loses ++; + h_to_h_stats[sched[week][game][VISITOR]] + [sched[week][game][HOST]].wins ++; + + if (divisions[sched[week][game][HOST]][CONFERENCE] == + divisions[sched[week][game][VISITOR]][CONFERENCE]) { + team_info_wi_conf[sched[week][game][HOST]].loses ++; + team_info_wi_conf[sched[week][game][VISITOR]].wins ++; + if (divisions[sched[week][game][HOST]][DIVISION] == + divisions[sched[week][game][VISITOR]][DIVISION]) { + team_info_wi_div[sched[week][game][HOST]].loses ++; + team_info_wi_div[sched[week][game][VISITOR]].wins ++; + } + } + } + else + if (scores[week][game][HOST] > scores[week][game][VISITOR]) { + team_info[sched[week][game][HOST]].wins ++; + team_info[sched[week][game][VISITOR]].loses ++; + + h_to_h_stats[sched[week][game][HOST]] + [sched[week][game][VISITOR]].wins ++; + h_to_h_stats[sched[week][game][VISITOR]] + [sched[week][game][HOST]].loses ++; + + if (divisions[sched[week][game][HOST]][CONFERENCE] == + divisions[sched[week][game][VISITOR]][CONFERENCE]) { + team_info_wi_conf[sched[week][game][HOST]].wins ++; + team_info_wi_conf[sched[week][game][VISITOR]].loses ++; + + if (divisions[sched[week][game][HOST]][DIVISION] == + divisions[sched[week][game][VISITOR]][DIVISION]) { + team_info_wi_div[sched[week][game][HOST]].wins ++; + team_info_wi_div[sched[week][game][VISITOR]].loses ++; + } + } + } + else { + team_info[sched[week][game][HOST]].ties ++; + team_info[sched[week][game][VISITOR]].ties ++; + + h_to_h_stats[sched[week][game][HOST]] + [sched[week][game][VISITOR]].ties ++; + h_to_h_stats[sched[week][game][VISITOR]] + [sched[week][game][HOST]].ties ++; + + if (divisions[sched[week][game][HOST]][CONFERENCE] == + divisions[sched[week][game][VISITOR]][CONFERENCE]) { + team_info_wi_conf[sched[week][game][HOST]].ties ++; + team_info_wi_conf[sched[week][game][VISITOR]].ties ++; + + if (divisions[sched[week][game][HOST]][DIVISION] == + divisions[sched[week][game][VISITOR]][DIVISION]) { + team_info_wi_div[sched[week][game][HOST]].ties ++; + team_info_wi_div[sched[week][game][VISITOR]].ties ++; + } + } + } + team_info[sched[week][game][HOST]].points_for += + scores[week][game][HOST]; + team_info[sched[week][game][HOST]].points_against += + scores[week][game][VISITOR]; + team_info[sched[week][game][VISITOR]].points_for += + scores[week][game][VISITOR]; + team_info[sched[week][game][VISITOR]].points_against += + scores[week][game][HOST]; + + if (divisions[sched[week][game][HOST]][CONFERENCE] == + divisions[sched[week][game][VISITOR]][CONFERENCE]) { + team_info_wi_conf[sched[week][game][HOST]].points_for += + scores[week][game][HOST]; + team_info_wi_conf[sched[week][game][HOST]].points_against += + scores[week][game][VISITOR]; + team_info_wi_conf[sched[week][game][VISITOR]].points_for += + scores[week][game][VISITOR]; + team_info_wi_conf[sched[week][game][VISITOR]].points_against += + scores[week][game][HOST]; + + if (divisions[sched[week][game][HOST]][DIVISION] == + divisions[sched[week][game][VISITOR]][DIVISION]) { + team_info_wi_div[sched[week][game][HOST]].points_for += + scores[week][game][HOST]; + team_info_wi_div[sched[week][game][HOST]].points_against += + scores[week][game][VISITOR]; + team_info_wi_div[sched[week][game][VISITOR]].points_for += + scores[week][game][VISITOR]; + team_info_wi_div[sched[week][game][VISITOR]].points_against += + scores[week][game][HOST]; + } + } + } + } + } + + void read_sched_into(FILE *STREAM,SCHED_TYPE sched) + { + BOOL error; + int num_seen[NUM_GAMES+1]; + int team_code,week_num,temp; + int AWAY,HOME,TEAM_FIELD,opponent,OPPON_FIELD,find_game; + char CH; + char str[10]; + + error = NO; + for (week_num=1;week_num<=num_games;week_num++) + num_seen[week_num] = 1; + + for (team_code=1;team_code<=NUM_TEAMS;team_code++) { + for (week_num=1;week_num<=num_games;week_num++) { + CH = (char) getc(STREAM); + while (white_space(CH)) CH = (char) getc(STREAM); + temp = 0; + while (!(white_space(CH))) { + str[temp] = CH; + temp ++; + CH = (char) getc(STREAM); + } + str[temp] = 0; + if (str[0] != '@') { + HOME = team_code; + TEAM_FIELD = HOST; + OPPON_FIELD = VISITOR; + AWAY = opponent = find_name(stderr,str); + } + else { + AWAY = team_code; + TEAM_FIELD = VISITOR; + OPPON_FIELD = HOST; + HOME = opponent = find_name(stderr,str+1); + } + if (opponent < team_code) /* already read in opponents information */ + { + for (find_game = 1; find_game<=num_seen[week_num]-1;find_game++) { + if (sched[week_num][find_game][TEAM_FIELD] == team_code) { + if (sched[week_num][find_game][OPPON_FIELD] != opponent) { + (void) printf("Error in opponent for %s(%d). Expected %s(%d), Found %s(%d). Week #%d\n" + ,team[team_code][FULL_NAME_0], team_code, + team[sched[week_num][find_game][OPPON_FIELD]][FULL_NAME_0], + sched[week_num][find_game][OPPON_FIELD], + team[opponent][FULL_NAME_0],opponent,week_num); + error = YES; + } + find_game = num_seen[week_num] + 2; + } + } + if (find_game == num_seen[week_num]) { + (void) printf("%s(%d) not found yet: team: %s(%d); week# %d; opp. str: %s\n", + team[opponent][FULL_NAME_0],opponent,team[team_code][FULL_NAME_0], + team_code,week_num,str); + error = YES; + } + } + else if (opponent != NUM_TEAMS + 1) { + int first_time; + + first_time = 0; + for (find_game = 1; find_game<=num_seen[week_num]-1;find_game++) { + if (sched[week_num][find_game][VISITOR] == team_code) + first_time = sched[week_num][find_game][HOST]; + if (sched[week_num][find_game][HOST] == team_code) + first_time = sched[week_num][find_game][VISITOR]; + } + if (first_time) { + (void) printf("%s(%d) has opponent %s(%d), but wants %s(%d); \n week# %d\n", + team[team_code][FULL_NAME_0],team_code, + team[first_time][FULL_NAME_0],first_time, + team[opponent][FULL_NAME_0],opponent,week_num); + error = YES; + } + else if ( num_seen[week_num] > NUM_TEAMS/2) { + (void) printf("ERROR: Week %d, to many games seen.\n",week_num); + error = YES; + } else { + sched[week_num][num_seen[week_num]][VISITOR] = AWAY; + sched[week_num][num_seen[week_num]][HOST] = HOME; + num_seen[week_num] ++; + } + } + } + } + + if (error) exit(1); + } + + void save_scores (FILE *msg_stream,char *file_name) + { + int game,week; + FILE *OUTPUT; + + if (!(OUTPUT = fopen(file_name,"w"))) { + (void) fprintf(msg_stream,"Can not write to %s. Not saved.\n",file_name); + } else { + for (week=1;week<=num_games+1; week++) { + for (game=1;game<=NUM_TEAMS/2; game++) { + (void) fprintf(OUTPUT," %d %d",scores[week][game][HOST], + scores[week][game][VISITOR]); + } + (void) fprintf(OUTPUT,"\n"); + } + (void) fclose(the_scores); + (void) fprintf(msg_stream,"Saved in %s.\n",file_name); + current_with_disk = YES; + } + } + + int in_fileP = 0; + + int main(int argc, char *argv[]) + { + BOOL argument_error = NO; + char *year; + FILE *in_file; + + {int i; + for (i=1;i<=NUM_TEAMS;i++) { + standings[i]=i; + conf_standings[i]=abs_standings[i]=i; + defence_ranks[i]=defence_ranks_nfl[i]=i; + offence_ranks[i]=offence_ranks_nfl[i]=i; + net_ranks[i]=net_ranks_nfl[i]=i; + } + } + + if (argc < 2) argument_error = YES; + else if (!strcmp(argv[1],"-p")) { + if (argc > 4) argument_error = YES; + preseason=YES; + year = argv[2]; + iyear = str_to_int(year); + num_games = NUM_PRESEASON_GAMES; + if (argc == 4) in_fileP = 3; + } + else if (argc <= 3) { + year = argv[1]; + iyear = str_to_int(year); + num_games = ( ((iyear >=78) && (iyear <= 89)) ? + NUM_GAMES_78_89 : NUM_GAMES); + if (argc == 3) in_fileP = 2; + } + else argument_error = YES; + + if (argument_error) { + (void) fprintf(stderr,"Usage: stats [-p] [input-file]\n is 2 digit year code.\n"); + exit(1); + } + + if (iyear <= 87) { + (void) strcpy(team[11][0],"sl"); + (void) strcpy(team[11][1],"St. Louis"); + } + + (void) strcpy(inp_sched,SCHED_0); + (void) strcat(inp_sched,year); + + if (preseason) + (void) strcat(inp_sched,".pre"); + + if (! (schedule = fopen(inp_sched,"r"))) { + (void) fprintf(stderr,"ERROR: Can not open %s.\n",inp_sched); + exit(1); + } + + read_sched_into(schedule,sched); + (void) fclose(schedule); + + if (in_fileP) { + in_file = fopen(argv[in_fileP],"r"); + if (!in_file) { + (void) fprintf(stderr,"ERROR: Can not open input file %s.\n", + argv[in_fileP]); + exit(1); + } + } + + (void) strcpy(input_score,SCORE_0); + (void) strcat(input_score,year); + + if (preseason) + (void) strcat(input_score,".pre"); + + if (! (the_scores = fopen(input_score,"r"))) { + int game,week; + + for (week=1;week<=num_games+1; week++) + for (game=1;game<=NUM_TEAMS/2; game++) { + scores[week][game][HOST] = -1; + scores[week][game][VISITOR] = -1; + } + (void) fprintf(stderr,"No score file. Creating one.\n"); + save_scores (stdout,input_score); + current_with_disk = NO; + } else { + int game,week; + + for (week=1;week<=num_games+1; week++) + for (game=1;game<=NUM_TEAMS/2; game++) { + if (feof(the_scores)) { + (void) fprintf(stderr,"ERROR: %s is not a legally formated score file.\n",input_score); + exit(1); + } + (void) fscanf(the_scores,"%d %d",&(scores[week][game][HOST]), + &(scores[week][game][VISITOR])); + } + (void) fclose(the_scores); + current_with_disk = YES; + } + compute_team_info (); + sort_all (); + + while ( !terminate ) { + if (in_fileP) + display_main_menu(stdout,in_file); + else display_main_menu(stdout,stdin); + } + if (in_fileP) (void) fclose(in_file); + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/football/stats.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/football/stats.h:1.1 *** /dev/null Tue Oct 5 16:05:48 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/football/stats.h Tue Oct 5 16:05:37 2004 *************** *** 0 **** --- 1,27 ---- + extern BOOL terminate; + extern int num_games; + extern int iyear; + extern BOOL a_wild_card(TEAM team); + extern BOOL a_champ(TEAM team); + extern int find_name(FILE *output,char name[]); + extern BOOL current_with_disk; + extern void save_scores(FILE *msg_stream,char *file_name); + extern char input_score[]; + extern SCHED_TYPE sched; + extern SCORES_TYPE scores; + extern TEAM_TYPE team; + extern void compute_team_info(void); + extern TEAMS_STATS team_info,team_info_wi_conf,team_info_wi_div; + extern ORDERING standings,conf_standings,abs_standings; + extern ORDERING defence_ranks,defence_ranks_nfl; + extern ORDERING offence_ranks,offence_ranks_nfl; + extern ORDERING net_ranks,net_ranks_nfl; + extern DIVISION_TYPE divisions; + + extern TEAM nfc_east_champ, nfc_central_champ, nfc_west_champ; + extern TEAM afc_east_champ, afc_central_champ, afc_west_champ; + extern TEAM nfc_wild_card1, nfc_wild_card2,nfc_wild_card3; + extern TEAM afc_wild_card1, afc_wild_card2,afc_wild_card3; + + extern BOOL team_plays[NUM_TEAMS+1][NUM_TEAMS+1]; + extern H_TO_H_STATS h_to_h_stats; From lattner at cs.uiuc.edu Tue Oct 5 16:07:26 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 16:07:26 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/ Message-ID: <200410052107.QAA27460@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 16:07:36 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 16:07:36 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/Makefile alabel.c arc.c circle.c closepl.c color.c cont.c dot.c draw_line.c erase.c extern.h fill.c fontname.c fontsize.c label.c libplot.h line.c linemod.c move.c openpl.c plot.c point.c rotate.c space.c Message-ID: <200410052107.QAA27516@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig: Makefile added (r1.1) alabel.c added (r1.1) arc.c added (r1.1) circle.c added (r1.1) closepl.c added (r1.1) color.c added (r1.1) cont.c added (r1.1) dot.c added (r1.1) draw_line.c added (r1.1) erase.c added (r1.1) extern.h added (r1.1) fill.c added (r1.1) fontname.c added (r1.1) fontsize.c added (r1.1) label.c added (r1.1) libplot.h added (r1.1) line.c added (r1.1) linemod.c added (r1.1) move.c added (r1.1) openpl.c added (r1.1) plot.c added (r1.1) point.c added (r1.1) rotate.c added (r1.1) space.c added (r1.1) --- Log message: Another benchmark without an input --- Diffs of the changes: (+1543 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/Makefile:1.1 *** /dev/null Tue Oct 5 16:07:35 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/Makefile Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,5 ---- + LEVEL = ../../../.. + + PROG = plot2fig + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/alabel.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/alabel.c:1.1 *** /dev/null Tue Oct 5 16:07:35 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/alabel.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,92 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + #include + #include + #ifdef sequent + #include + #else + #include + #endif + #include + #include "libplot.h" + #include "extern.h" + + /* ALABEL takes three arguments X_JUSTIFY, Y_JUSTIFY, and S and places + the label S according to the x and y axis adjustments specified in + X_JUSTIFY and Y_JUSTIFY respectively. X_JUSTIFY is a character + containing either l, c, or r for left, center or right justified with + respect to the current x coordinate. Y_JUSTIFY is a character + containing either b, c, or t for placing the bottom center or top of + the label even with the current y coordinate. S is a string containing + the label. The current point is moved to follow the end of the text. */ + + int alabel (int x_justify, int y_justify, char *s) + { + /* int i; this variable is never used */ + char *p; + int x_justification = 0; + double y_offset = 0.; + + draw_line (); + switch( x_justify) { + case 'l': + x_justification = 0; + break; + case 'c': + x_justification = 1; + break; + case 'r': + x_justification = 2; + break; + } + switch( y_justify) { + case 't': + y_offset = 1.1; + break; + case 'c': + y_offset = 0.5; + break; + case 'b': + y_offset = 0.0; + break; + } + + /* ignore leading white space */ + p = s; + while (isspace(*p)) + p++; + + /* only output the string if it contains non-whitespace characters. */ + if (strlen(p)) + printf( "%d %d %d %d %d %d %d %.3f %d %d %d %d %d %s\1\n", + 4, /* text object */ + x_justification, /* horzontal justification */ + font_id, /* font */ + font_size, /* point size */ + 0, /* pen */ + 0, /* color */ + 0, /* depth */ + text_rotation, /* angle of rotation (float) */ + 0, /* flags */ + 8, /* height (pixels) */ + 8, /* length (pixels) */ + (int) ((last_x - x_input_min)/ x_scale + x_output_min), + (int) ((last_y - y_input_min)/ y_scale + y_output_min + + font_size * y_offset * 72 / 80), + p); + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/arc.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/arc.c:1.1 *** /dev/null Tue Oct 5 16:07:35 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/arc.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,60 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the arc routine, which is a standard part of the plot + library. It draws an arc with the center at xc,yc, the beginning at + x0,y0 and the ending at x1,y1 */ + + #include + #include + #ifdef sequent + #include + #else + #include + #endif + /* + extern int printf(); + extern int fprintf(); + #ifndef mips + extern char *sprintf(); + #endif + extern int fputs(), fputc(); + */ + + #include "libplot.h" + #include "extern.h" + + int arc (int xc, int yc, int x0, int y0, int x1, int y1) + { + draw_line (); + printf("%d %d %d %d %d %d %d %d %.3f %d %d %d %.3f %.3f %d %d %d %d %d %d\n", + 5 /* arc object */, 1, line_style, 0 /* thickness */, + 0 /* black */, 0, 0, fill_level, + dash_length, 0 /* clockwise */, + 0, 0, + (int) ((xc - x_input_min)/ x_scale + x_output_min), + (int) ((yc - y_input_min)/ y_scale + y_output_min), + (int) ((x0 - x_input_min)/ x_scale + x_output_min), + (int) ((y0 - y_input_min)/ y_scale + y_output_min), + (int) ((x1 - x_input_min)/ x_scale + x_output_min), + (int) ((y1 - y_input_min)/ y_scale + y_output_min), + (int) ((x1 - x_input_min)/ x_scale + x_output_min), + (int) ((y1 - y_input_min)/ y_scale + y_output_min)); + + move_nasko (xc, yc); + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/circle.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/circle.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/circle.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,43 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the circle routine, which is a standard part of the plot + library. It draws a circle given the center x,y and the radius */ + + #include + #include + #ifdef sequent + #include + #else + #include + #endif + #include "libplot.h" + #include "extern.h" + /* + extern int printf(); + extern int fprintf(); + #ifndef mips + extern char *sprintf(); + #endif + extern int fputs(), fputc(); + */ + + int circle (int x, int y, int r) + { + arc (x, y, x+r, y, x+r, y); + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/closepl.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/closepl.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/closepl.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,37 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the closepl routine, which is a standard part of the plot + library. Normally it closes the plotting device. */ + + #include + #ifdef sequent + #include + #else + #include + #endif + #include "libplot.h" + #include "extern.h" + extern int fputs(), fputc(); + + int closepl (void) + { + draw_line (); + return 0; + } + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/color.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/color.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/color.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,37 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the color routine, which is an extension to the plot + library. It changes the color of the following drawing operations. */ + + #include "libplot.h" + #include "extern.h" + + /* FGCOLOR_RED, FGCOLOR_GREEN and FGCOLOR_BLUE indicate the foreground + color of all plot. For each the range of intensity is from 0 to 1 so + that a value of (0,0,0) represents black and a value of (1,1,1) + indicates white. */ + + double fgcolor_red=0., fgcolor_green=0., fgcolor_blue=0.; + + int color ( int red, int green, int blue) + { + fgcolor_red = red / 0xffff; + fgcolor_green = green / 0xffff; + fgcolor_blue = blue / 0xffff; + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/cont.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/cont.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/cont.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,64 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the cont routine, which is a standard part of the plot + library. It continues a line from the last point drawn to the point + specified by x and y. + */ + #include + #include "libplot.h" + #include "extern.h" + + int last_x=0, last_y = 0; /* location of the last coordinates used */ + + int PointsInLine=0; + + int cont(int x, int y) + { + if (PointsInLine <= 1) + { + printf( "%d %d %d %d %d %d %d %d %.3f %d %d %d\n\t", + 2, /* polyline object */ + 1, /* polyline subtype */ + line_style, /* style */ + 1, /* thickness */ + 0, /* color */ + 0, /* depth */ + 0, /* pen */ + fill_level, /* area fill */ + dash_length, /* style val */ + 0, /* radius */ + 0, /* forward arrow */ + 0 /* backward arrow */ + ); + } + if (PointsInLine == 1) + { + printf(" %d %d", + (int) ((last_x - x_input_min)/ x_scale + x_output_min), + (int) ((last_y - y_input_min)/ y_scale + y_output_min)); + } + + PointsInLine++; + printf(" %d %d", + (int) ((x - x_input_min)/ x_scale + x_output_min), + (int) ((y - y_input_min)/ y_scale + y_output_min)); + last_x = x; + last_y = y; + + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/dot.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/dot.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/dot.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,31 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the dot routine, which is an extension to the plot + library. this is an extentsion and may be modified. Although I have + seen support for this in other plot(1g) programs, I haven't yet found + out exactly what `dot' is supposed to do, so it is not yet implemented + fully. */ + + #include "libplot.h" + #include "extern.h" + + int dot (int x, int y, int dx, int n, char pattern) + { + point (x, y); + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/draw_line.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/draw_line.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/draw_line.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,56 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the draw_line routine, which is used by the other plot + library routines. It marks the end of a polyline obect in the output. */ + + #include + #include + #ifdef sequent + #include + #else + #include + #endif + /* + extern int perror(); + extern int exit(); + extern int printf(); + extern int fprintf(); + #ifndef mips + extern char *sprintf(); + #endif + extern int fputs(), fputc(); + #ifndef hpux + extern void *malloc(); + extern void *realloc(); + #endif + */ + + #include "libplot.h" + #include "extern.h" + + /* draw a line using all the accumulated points if there are any. */ + + int draw_line (void) + { + if (PointsInLine > 1) + { + printf( " 9999 9999\n"); + PointsInLine = 0; + } + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/erase.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/erase.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/erase.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,29 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the erase routine, which is a standard part of the plot + library. It erases the page. + */ + + #include "libplot.h" + #include "extern.h" + + int erase (void) + { + return 0; + } + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/extern.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/extern.h:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/extern.h Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,44 ---- + /* plot, unix plot to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute + plot, but only under the conditions described in the GNU General + Public License. A copy of this license is supposed to have been given + to you along with plot so you can know your rights and + responsibilities. It should be in a file named COPYING. Among other + things, the copyright notice and this notice must be preserved on all + copies. */ + + /* this file contains all the exernal references between plot library + functions. The are not guaranteed to exist for a particular device + and thus are not made available to the user in general. */ + + extern int font_id; + extern int font_size; + extern float text_rotation; + extern int line_style; + extern int last_x, last_y; + extern int PointsInLine; + extern float dash_length; + extern int fill_level; + + extern double x_input_min; /* minimum input x coordinate */ + extern double y_input_min; /* minimum input y coordinate */ + extern double x_output_min; /* minimum output x coordinate */ + extern double y_output_min; /* minimum output y coordinate */ + extern double x_output_max; /* maximum output x coordinate */ + extern double y_output_max; /* maximum output y coordinate */ + extern double scaleup; /* maximum input to output scaleing of x and y */ + extern double x_scale; /* input to output scaleing for x */ + extern double y_scale; /* input to output scaleing for y */ + + /* For convenience - some machines do not define M_PI. */ + #ifndef M_PI + #define M_PI 3.14159265358979323846264 + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/fill.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/fill.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/fill.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,51 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + /* This file is the fill routine, which is an extension to the plot + library. It changes the grey level of the fill pattern for all closed + paths of the following drawing operations. */ + + #include "libplot.h" + #include "extern.h" + + int fill_level = 0; /* default, no fill */ + + /* FILL sets the intensity of the filler for closed paths. LEVEL ranges + from 1 to 0xFFFF. A value of 1 represents black and a value of 0xFFFF + indicates white. A value of 0 represents no fill - transparent. */ + + int fill (int level) + { + if (level == 0) + { + fill_level = 0; + } + else + { + fill_level = 5 * ((double)level - 1.)/0xFFFE; + /* The value of fill level should be between 1 and 5, + which is enforced here. */ + if (fill_level > 5) + { + fill_level = 5; + } + else if (fill_level < 1) + { + fill_level = 1; + } + } + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/fontname.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/fontname.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/fontname.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,125 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* FONTNAME takes a string argument S containing the name of the + desired current font and sets the current font to that name. */ + + #include + #ifdef sequent + #include + #else + #include + #endif + #include "libplot.h" + #include "extern.h" + extern int fprintf(FILE *, const char *, ...); + + /* a simple fixed string matcher. match returns + 1 if there is a match for s1 in s2, else 0. */ + int match (char *s1, char *s2) + { + int len2, i; + len2 = strlen (s2); + + for (i=0; i + + int fontname(char *s) + { + int r; + regex_t *res; + + r = regcomp (res,s,1); + if (!r) + { + fprintf (stderr, "error in matching fontname!\n"); + fprintf (stderr, "Fontname `%s' ignored.\n", s); + return 0; + } + + #define re_exec(x) regexec(res,x,1,&res,1) + + if (re_exec("typewriter") + || re_exec("courier")) + font_id = 5; + else if (re_exec("modern")) + font_id = 4; + else if (re_exec("italic") + || re_exec("oblique")) + font_id = 3; + else if (re_exec("bold")) + font_id = 2; + else if (re_exec("times") + || re_exec("roman")) + font_id = 2; + else + fprintf (stderr, "Unrecognized font name `%s' ignored.\n", s); + + return 0; + } + + #else + + int fontname(char *s) + { + char *res; + + res = (char *) re_comp (s); + if (res) + { + fprintf (stderr, "error in matching fontname: %s\n", res); + fprintf (stderr, "Fontname `%s' ignored.\n", s); + return 0; + } + + if (re_exec("typewriter") + || re_exec("courier")) + font_id = 5; + else if (re_exec("modern")) + font_id = 4; + else if (re_exec("italic") + || re_exec("oblique")) + font_id = 3; + else if (re_exec("bold")) + font_id = 2; + else if (re_exec("times") + || re_exec("roman")) + font_id = 2; + else + fprintf (stderr, "Unrecognized font name `%s' ignored.\n", s); + + return 0; + } + + #endif Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/fontsize.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/fontsize.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/fontsize.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,30 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* FONTSIZE takes a single integer argument SIZE and sets the font + size accordingly. */ + + #include "libplot.h" + #include "extern.h" + + int font_size = 12; + + int fontsize(int size) + { + font_size = size; + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/label.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/label.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/label.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,30 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the label routine, which is a standard part of the plot + library. It draws a label at the most recently used coordinate. */ + + #include + #include + #include "libplot.h" + #include "extern.h" + + int label(char *s) + { + (void) alabel ('l', 'b', s); + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/libplot.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/libplot.h:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/libplot.h Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,55 ---- + /* plot, unix plot to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone for the + consequences of using it or for whether it serves any particular purpose or + works at all, unless he says so in writing. Refer to the GNU General Public + License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, but + only under the conditions described in the GNU General Public License. A copy + of this license is supposed to have been given to you along with plot so + you can know your rights and responsibilities. It should be in a file named + COPYING. Among other things, the copyright notice and this notice must be + preserved on all copies. */ + + #ifndef _PLOT3_H + #define _PLOT3_H + + /* This elides the argument prototypes if the compiler does not + supprort them. The name protarg is chosen in hopes that it will not + collide with any others. */ + #ifdef __STDC__ + #define protarg(a) a + #else + #define protarg(a) () + #endif + + /* the standard library of plot functions */ + extern int arc protarg ((int xc, int yc, int x0, int y0, int x1, int y1)); + extern int circle protarg ((int x, int y, int r)); + extern int closepl protarg (()); + extern int cont protarg ((int x, int y)); + extern int erase protarg (()); + extern int label protarg ((char *s)); + extern int line protarg ((int x0, int y0, int x1, int y1)); + extern int linemod protarg ((char *s)); + extern int move_nasko protarg ((int x, int y)); + extern int openpl protarg (()); + extern int point protarg ((int x, int y)); + extern int space protarg ((int x0, int y0, int x1, int y1)); + + /* Extensions to the library for postscript */ + extern int alabel protarg ((int x_justify, int y_justify, char *s)); + extern int color protarg ((int red, int green, int blue)); + extern int draw_line protarg (()); + extern int fill protarg ((int level)); + extern int fontname protarg ((char *s)); + extern int fontsize protarg ((int size)); + extern int rotate protarg ((int x, int y, int angle)); + + /* internally used routines */ + extern int draw_line protarg (()); + + #endif /* _PLOT3_H */ Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/line.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/line.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/line.c Tue Oct 5 16:07:24 2004 *************** *** 0 **** --- 1,27 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + /* This file is the line routine, which is a standard part of the plot + library. It draws a line from coordinate x0,y0 to x1,y1 */ + #include "libplot.h" + #include "extern.h" + + int line (int x0, int y0, int x1, int y1) + { + move_nasko (x0,y0); + cont (x1,y1); + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/linemod.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/linemod.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/linemod.c Tue Oct 5 16:07:25 2004 *************** *** 0 **** --- 1,88 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the linemod routine, which is a standard part of the plot + library. It sets the line type according to the name contained in + the string argument s */ + + #include + #include + #ifdef sequent + #include + #else + #include + #endif + #include "libplot.h" + #include "extern.h" + /* + extern int printf(); + extern int fprintf(); + #ifndef mips + extern char *sprintf(); + #endif + extern int fputs(), fputc(); + */ + + int line_style = 0; /* solid */ + + float dash_length = 10.0; /* short dashed */ + + int linemod(char *s) + { + if ((strcmp( s, "longdashed") == 0) + || (strcmp( s, "long-dashed") == 0)) + { + line_style = 1; + dash_length = 20.0; + } + else if (strcmp( s, "disconnected") == 0) + { + line_style = 2; + dash_length = 999.0; + } + else if ((strcmp( s, "dotdashed") == 0) + || (strcmp( s, "dot-dashed") == 0)) + { + line_style = 1; + dash_length = 4.0; + } + else if (strcmp( s, "dotted") == 0) + { + line_style = 2; + dash_length = 2.0; + } + else if (strcmp( s, "solid") == 0) + { + line_style = 0; + dash_length = 1.0; + } + else if ((strcmp( s, "shortdashed") == 0) + || (strcmp( s, "short-dashed") == 0)) + { + line_style = 1; + dash_length = 10.0; + } + else + { + fprintf( stderr, "Unrecognized line mode `%s' ignored. Using solid.\n", s); + /* Set the line mode to SOLID if an unsupported mode is requested. */ + line_style = 0; + dash_length = 1.0; + } + + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/move.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/move.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/move.c Tue Oct 5 16:07:25 2004 *************** *** 0 **** --- 1,33 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the move routine, which is a standard part of the plot + library. It switches the device to vector plot mode and plots a + point at the given coordinate. + */ + #include + #include "libplot.h" + #include "extern.h" + + int move_nasko(int x, int y) + { + draw_line (); + last_x = x; + last_y = y; + PointsInLine=1; + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/openpl.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/openpl.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/openpl.c Tue Oct 5 16:07:25 2004 *************** *** 0 **** --- 1,58 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the openpl routine, which is a standard part of the plot + library. It normally opens the device. We just print out the + postscript prologue */ + + #include + #include + #ifdef sequent + #include + #else + #include + #endif + #include "libplot.h" + #include "extern.h" + /* + extern int perror(); + extern int exit(); + extern int printf(); + extern int fprintf(); + extern int fclose(); + extern int fread(); + extern int fwrite(); + #ifndef mips + extern char *sprintf(); + #endif + extern int fputs(), fputc(); + #ifndef hpux + extern void *malloc(); + extern void *realloc(); + #endif + */ + + int openpl(void) + { + printf( "#FIG 2.0\n"); + printf( "%d %d\n", + 80, /* pixels per inch */ + 2 /* origin in lower left corner */ + ); + + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/plot.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/plot.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/plot.c Tue Oct 5 16:07:25 2004 *************** *** 0 **** --- 1,439 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the main routine for plot. + + It includes code to read the plot file and call plot functions + to draw the graphics. */ + + #include + #include "/usr/include/stdlib.h" + #include + #ifdef sequent + #include + #else + #include + #endif + #include + #include "libplot.h" + + /* + extern int perror(); + extern int exit(); + extern int printf(); + extern int fprintf(); + extern int fclose(); + #ifndef mips + extern char *sprintf(); + #endif + #ifndef hpux + extern void *malloc(); + extern void *realloc(); + #endif + extern int fputs(); + */ + extern void perror(const char *s); + + /* #include "../COPYING" */ + + enum plot_instruction + { + ALABEL = 'T', + ARC = 'a', + CIRCLE = 'c', + COLOR = 'C', + CONT = 'n', + ERASE = 'e', + FILL = 'L', + FONT = 'F', + FONTSIZE = 'S', + LABEL = 't', + LINE = 'l', + LINEMOD = 'f', + MOVE = 'm', + POINT = 'p', + ROTATE = 'r', + SPACE = 's' + }; + + /* This flag specifies that the input contains unsigned (if zero) or + signed (if nonzero) two byte intgers. The default is signed. */ + int signed_input = 1; + + /* read in two byte intgers with high_byte_first. The default is to read the low + byte first. */ + int high_byte_first = 0; + + /* guess_byte_order is a flag which, if non-zero, indicated that the function + find_byte_order should be used to guess the byte order for the input file. */ + int guess_byte_order = 1; + + /* swap_bytes returns the bottom two bytes of its integer argument with + their bytes reversed. */ + + int swap_bytes(int x) + { + unsigned char a, b; + a = x & 0xff; + b = (x >> 8) & 0xff; + return ((a << 8)|b); + } + + /* This is a set of known values for the maximum x (abscissa) values + specified in the plot size command for known devices. Using this + set we can construct a heuristic proceedure for recognizing plot + files in which the bytes of two byte integers are reversed. We can + recognize these files by looking for size commands containing these + known sizes in byte reversed form. The last entry should be 0. */ + + int known_size[32] = { + 504, /* plot3d output 504x504 */ + 2048, /* versatek plotter 2048x2048 */ + 2100, /* plot3d output */ + 3120, /* Tektronix 4010 terminal 3120x3120 */ + 4096, /* GSI 300 terminal 4096x4096 */ + 0 /* the last entry should be 0 */ + }; + + /* find_byte_order takes four integer arguments and matches third one + against a set of known values (sizes, see above). If there is a match + it merely returns. If there is no match, it check each of the values + again with the bottom two bytes reversed. If such a match is found, the + bottom two bytes of each argument is reversed, the high_byte_first flag + is inverted to indicated how two byte integers should be read and the + runction returns. */ + + void find_byte_order(int *x0, int *y0, int *x1, int * y1) + { + int i; + for (i=0; known_size[i]!=0; i++) + { + if (*x1 == known_size[i]) + return; + } + /* now check to see if reversing the bytes allows a match... */ + for (i=0; known_size[i]!=0; i++) + { + if (*x1 == swap_bytes (known_size[i])) + { + *x0 = swap_bytes( *x0); + *y0 = swap_bytes( *y0); + *x1 = swap_bytes( *x1); + *y1 = swap_bytes( *y1); + high_byte_first = ! high_byte_first; + return; + } + } + } + + /* Read a byte */ + + #define read_byte(stream) (getc (stream)) + + /* Read a coordinate - a two byte integer. */ + + int coord(FILE *input) + { + int x; + if ( high_byte_first ) + { + x = ((char) read_byte(input)) << 8; /* get sign from high byte */ + x |= read_byte(input) & 0xFF; /* not from low byte */ + } + else + { + x = read_byte (input) & 0xFF; /* ingnore sign in low byte */ + x |= ((char) read_byte (input)) << 8; /* get sign from high byte */ + } + if ( ! signed_input ) + { + x &= 0xFFFF; + } + + return x; + } + + /* Read a string, change termination to null. + note: string (buffer) reads a newline terminated string. */ + + void read_string (FILE *input, char *buffer, int buffer_length) + { + int length=0; + char termination = '\n'; + char c = '\0'; + + while (!feof (input)) + { + if (length > buffer_length) + { + buffer_length *= 2; + buffer = (char *) realloc (buffer, buffer_length); + if (buffer <= (char *) 0) + { + perror ("realloc failed:"); + exit (-1); + } + } + c = read_byte (input); + if (c == termination) + break; + buffer [length++] = c; + } + + buffer [length] = '\0'; /* null terminate label */ + } + + + /* read_plot reads a plot file from the standard input and calls + a plot function according to each plot instruction found in the + file. */ + + void read_plot(FILE *in_stream, char *buffer, int buffer_length) + { + char x_adjust, y_adjust; + int x0, y0, x1, y1, x2, y2; + int instruction; + + instruction = read_byte (in_stream); + while (!feof (in_stream)) + { + switch (instruction) + { + /* Note: we must get all but the last argument before calling to + ensure reading them in the proper order. */ + + case ALABEL: + x_adjust = read_byte (in_stream); + y_adjust = read_byte (in_stream); + read_string (in_stream, buffer, buffer_length); + alabel (x_adjust, y_adjust, buffer); + break; + case ARC: + x0 = coord (in_stream); + y0 = coord (in_stream); + x1 = coord (in_stream); + y1 = coord (in_stream); + x2 = coord (in_stream); + y2 = coord (in_stream); + arc (x0, y0, x1, y1, x2, y2); + break; + case CIRCLE: + x0 = coord (in_stream); + y0 = coord (in_stream); + x1 = coord (in_stream); + circle (x0, y0, x1); + break; + case COLOR: + x0 = coord (in_stream)&0xFFFF; + y0 = coord (in_stream)&0xFFFF; + x1 = coord (in_stream)&0xFFFF; + color (x0, y0, x1); + break; + case CONT: + x0 = coord (in_stream); + y0 = coord (in_stream); + cont (x0, y0); + break; + case ERASE: + erase (in_stream); + break; + case FILL: + fill (coord (in_stream)&0xFFFF); break; + case FONT: + read_string (in_stream, buffer, buffer_length); + fontname (buffer); + break; + case FONTSIZE: + fontsize (coord (in_stream)); + break; + case LABEL: + read_string (in_stream, buffer, buffer_length); + label (buffer); + break; + case LINE: + x0 = coord (in_stream); + y0 = coord (in_stream); + x1 = coord (in_stream); + y1 = coord (in_stream); + line (x0, y0, x1, y1); + break; + case LINEMOD: + read_string (in_stream, buffer, buffer_length); + linemod (buffer); + break; + case MOVE: + x0 = coord (in_stream); + y0 = coord (in_stream); + move_nasko (x0, y0); + break; + case POINT: + x0 = coord (in_stream); + y0 = coord (in_stream); + point (x0, y0); + break; + case ROTATE: + x0 = coord (in_stream); + y0 = coord (in_stream); + x1 = coord (in_stream); + rotate (x0, y0, x1); + break; + case SPACE: + x0 = coord (in_stream); + y0 = coord (in_stream); + x1 = coord (in_stream); + y1 = coord (in_stream); + if (guess_byte_order) + find_byte_order(&x0, &y0, &x1, &y1); + space (x0, y0, x1, y1); + break; + default: + fprintf (stderr, "Unrecognized plot command `%c' ignored.\n", instruction); + } + instruction = read_byte (in_stream); + } + return; + } + + int main (int argc, char *argv[]) + { + int i; + char *buffer; + int buffer_length; + int named_plot=0; /* count named plot files on command line. */ + int show_usage=0; /* remember whether to output usage message. */ + int opened=0; /* remember whether we have opened output. */ + + buffer_length = 1024; + buffer = (char *) malloc (buffer_length); + if (buffer <= (char *) 0) + { + perror ("malloc failed:"); + exit (-1); + } + + for (i = 1; i < argc; i++) + { + if ((strcmp (argv [i], "-fontsize") == 0) + || (strcmp (argv [i], "-fs") == 0)) + { + /* Sizes supported by X: 8, 10, 12, 14, 18, and 24. */ + fontsize (atoi (argv[i+1])); + i += 1; + } + else if ((strcmp (argv [i], "-fontname") == 0) + || (strcmp (argv [i], "-fn") == 0)) + { + fontname (argv [i+1]); + i += 1; + } + else if ((strcmp (argv [i], "-high-byte-first") == 0) + || (strcmp (argv [i], "-h") == 0)) + { + guess_byte_order = 0; + high_byte_first = 1; + } + else if ((strcmp (argv [i], "-low-byte-first") == 0) + || (strcmp (argv [i], "-l") == 0)) + { + guess_byte_order = 0; + high_byte_first = 0; + } + else if ((strcmp (argv [i], "-warranty") == 0) + || (strcmp (argv [i], "-copying") == 0)) + { + /* + for (i=0; copy_notice[i][0]>0; i++) + fputs (copy_notice[i], stdout); + */ + named_plot++; + } + else if ((strcmp (argv [i], "-help") == 0) + || (strcmp (argv [i], "-V") == 0)) + { + printf ("%s version %s\n", argv[0], "0.0"); + show_usage++; + named_plot++; + } + else if ((strcmp (argv [i], "-signed") == 0)) + { + signed_input=1; + } + else if ((strcmp (argv [i], "-unsigned") == 0)) + { + signed_input=0; + } + else if ((strcmp (argv [i], "-") == 0)) + { + read_plot (stdin, buffer, buffer_length); + named_plot++; + } + else + { + FILE *filep; + filep = fopen ( argv [i], "r"); + if (filep == NULL) + { + fprintf (stderr, "Unrecognized option or file `%s' ignored.\n", + argv [i]); + show_usage++; + } + else + { + named_plot++; + if (!opened) + { + openpl (); + opened ++; + } + read_plot (filep, buffer, buffer_length); + fclose (filep); + } + } + } + + + + /* if there were no named plot files on the command line, then read + the standard input. */ + if (named_plot == 0) + { + if (!opened) + { + openpl (); + opened ++; + } + read_plot (stdin, buffer, buffer_length); + } + if (opened) + closepl(); + + if ( show_usage || !opened) + { + fprintf (stderr, "\n\ + usage: %s [-fontsize|-fs SIZE] [-high-byte-first|-h]\n\ + [-low-byte-first|-l] [-fontname|-fn FONTNAME]\n\ + [-help|-V] [-copying|-warranty] [PLOT_FILE_NAMES ...]\n", + *argv); + fprintf (stderr, "\n\ + %s version 0.9, Copyright (C) 1989 Free Software Foundation, Inc.\n\ + %s comes with ABSOLUTELY NO WARRANTY. This is free software, and\n\ + you are welcome to redistribute it. Type `%s -warranty' for warranty\n\ + details and copying conditions.\n\n", + *argv, *argv, *argv); + } + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/point.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/point.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/point.c Tue Oct 5 16:07:25 2004 *************** *** 0 **** --- 1,28 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + /* This file is the point routine, which is a standard part of the plot + library. It draws a point at the coordinate x,y. */ + + #include "libplot.h" + #include "extern.h" + + int point(int x, int y) + { + move_nasko (x, y); + cont (x, y); + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/rotate.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/rotate.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/rotate.c Tue Oct 5 16:07:25 2004 *************** *** 0 **** --- 1,32 ---- + /* plot, unix plot file to graphics device translators. + Copyright (C) 1989 Free Software Foundation, Inc. + + plot is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. + Refer to the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute plot, + but only under the conditions described in the GNU General Public + License. A copy of this license is supposed to have been given to you + along with plot so you can know your rights and responsibilities. It + should be in a file named COPYING. Among other things, the copyright + notice and this notice must be preserved on all copies. */ + + + /* This file is the arc routine, which is an extension to the plot + library. It rotates subsequent labels to the given angle in degress + from the horizontal */ + + #include + #include "libplot.h" + #include "extern.h" + + float text_rotation=0.0; + + int rotate (int w, int h, int angle) + { + text_rotation = angle * M_PI / 180.0; + return 0; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/space.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/space.c:1.1 *** /dev/null Tue Oct 5 16:07:36 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/plot2fig/space.c Tue Oct 5 16:07:25 2004 *************** *** 0 **** --- 1,49 ---- + /* libtek, a library of functions for tektronics 4010 compatible devices. + Copyright (C) 1989 Free Software Foundation, Inc. + + libtek is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY. No author or distributor accepts responsibility to anyone for the + consequences of using it or for whether it serves any particular purpose or + works at all, unless he says so in writing. Refer to the GNU General Public + License for full details. + + Everyone is granted permission to copy, modify and redistribute libtek, but + only under the conditions described in the GNU General Public License. A copy + of this license is supposed to have been given to you along with libtek so + you can know your rights and responsibilities. It should be in a file named + COPYING. Among other things, the copyright notice and this notice must be + preserved on all copies. */ + + /* This file is the space routine, which is a standard part of the plot + library. It sets the lower left and upper right corners of the page. The + plot will be scaled so that these coners fit the largest renderable area on + the page. */ + + #include + #include "libplot.h" + #include "extern.h" + + double x_input_min = 0.; /* minimum input x coordinate */ + double y_input_min = 0.; /* minimum input y coordinate */ + /* Latex has troubles with plots larger than 6 inches (480). */ + /* The range (60,660) to (540,180) centers the plot in the fig window. */ + double x_output_min = 60.; /* minimum output x coordinate */ + double y_output_min = 660.; /* minimum output y coordinate */ + double x_output_max = 540.; /* maximum output x coordinate */ + double y_output_max = 180.; /* maximum output y coordinate */ + double scaleup = 1.; /* maximum input to output scaleing of x and y */ + double x_scale = 1.; /* input to output scaleing for x */ + double y_scale = 1.; /* input to output scaleing for y */ + + int space (int x0, int y0, int x1, int y1) + { + x_input_min = x0; + y_input_min = y0; + x_scale = (x1 - x0)/(x_output_max - x_output_min); + y_scale = (y1 - y0)/(y_output_max - y_output_min); + if (fabs(x_scale) > fabs(y_scale)) + scaleup = fabs (x_scale); + else + scaleup = fabs (y_scale); + return 0; + } From lattner at cs.uiuc.edu Tue Oct 5 16:08:43 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 16:08:43 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/ Message-ID: <200410052108.QAA27758@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator: --- Log message: Directory /home/vadve/shared/PublicCVS/llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator added to the repository --- Diffs of the changes: (+0 -0) From lattner at cs.uiuc.edu Tue Oct 5 16:08:51 2004 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 5 Oct 2004 16:08:51 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/Makefile boolean.h constants.h convert.c convert.h debugger.c debugger.h define-instr-tab.h format.c format.h instruct.c instruct.h instruct2.c instruct2.h interupt.c interupt.h load.h loadexe.c loadexe.h machine.c machine.h memory.c memory.h print.c print.h sim_debug.c sim_debug.h stringI.c stringI.h sym_tab.c sym_tab.h Message-ID: <200410052108.QAA27826@apoc.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator: Makefile added (r1.1) boolean.h added (r1.1) constants.h added (r1.1) convert.c added (r1.1) convert.h added (r1.1) debugger.c added (r1.1) debugger.h added (r1.1) define-instr-tab.h added (r1.1) format.c added (r1.1) format.h added (r1.1) instruct.c added (r1.1) instruct.h added (r1.1) instruct2.c added (r1.1) instruct2.h added (r1.1) interupt.c added (r1.1) interupt.h added (r1.1) load.h added (r1.1) loadexe.c added (r1.1) loadexe.h added (r1.1) machine.c added (r1.1) machine.h added (r1.1) memory.c added (r1.1) memory.h added (r1.1) print.c added (r1.1) print.h added (r1.1) sim_debug.c added (r1.1) sim_debug.h added (r1.1) stringI.c added (r1.1) stringI.h added (r1.1) sym_tab.c added (r1.1) sym_tab.h added (r1.1) --- Log message: Another benchmark without an input --- Diffs of the changes: (+4482 -0) Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/Makefile diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/Makefile:1.1 *** /dev/null Tue Oct 5 16:08:50 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/Makefile Tue Oct 5 16:08:39 2004 *************** *** 0 **** --- 1,6 ---- + LEVEL = ../../../.. + + PROG = simulator + LDFLAGS = -lm + include $(LEVEL)/MultiSource/Makefile.multisrc + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/boolean.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/boolean.h:1.1 *** /dev/null Tue Oct 5 16:08:51 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/boolean.h Tue Oct 5 16:08:39 2004 *************** *** 0 **** --- 1,6 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================= boolean.h ================================= */ + /* Just makes BOOLEAN another name for int. */ + typedef int BOOLEAN; Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/constants.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/constants.h:1.1 *** /dev/null Tue Oct 5 16:08:51 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/constants.h Tue Oct 5 16:08:39 2004 *************** *** 0 **** --- 1,61 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================= constants.h =============================== */ + /* A collection of commonly used constants for the assembler. */ + + + /* DEBUG_FLAG_1 Controls whether certain lines of the program. */ + /* Execution or non-execution of these lines aids in */ + /* Debugging the program. */ + #define DEBUG_FLAG_1 0 + + /* LABEL_SIZE_1 Size of the largest valid LABEL in characters */ + #define LABEL_SIZE_1 8 + + /* MEM_SIZE_1 Size of SIC/XE main memory in bytes */ + /* NOTE: 2^20 = 1048576 */ + #define MEM_SIZE_1 1048576 + + /* MEM_ADDR_SIZE_1 Number of BITS in an address {log2(MEM_SIZE_1)} */ + #define MEM_ADDR_SIZE_1 20 + + /* BITS_PER_WORD_1 Number of BITS in a WORD */ + #define BITS_PER_WORD_1 24 + + /* MAX_INT_1 Biggest integer+1: 2^BITS_PER_WORD_1 */ + #define MAX_INT_1 16777216 + + /* BITS_PER_HALFBYTE_1 Number of BITS in a Half BYTE */ + #define BITS_PER_HALFBYTE_1 4 + + /* BITS_PER_BYTE_2 Number of BITS in a BYTE */ + #define BITS_PER_BYTE_2 8 + + /* HEX_CHAR_PER_BYTE_1 Number of hexidecimal characters (ASCII) must be */ + /* used to produce a 1 BYTE value. */ + #define HEX_CHAR_PER_BYTE_1 2 + + /* LARGEST_INSTRUCT_SIZE_1 Size in BITS of the the largest instruction in */ + /* SIC/XE. Format 4 is 32 bits */ + #define LARGEST_INSTRUCT_SIZE_1 32 + + /* MAX_PC_RELATIVE_1 Smallest number that will NOT fit in a PC relative*/ + /* address. {4096 = 2^12} */ + #define MAX_PC_RELATIVE_1 4096 + + /* GLOBAL_1 Module name for Global labels -- used by LOADER. */ + #define GLOBAL_1 "_GLOBAL " + + /* -------------------------- Boolean Constants ---------------------------- */ + #define FALSE_1 0 + #define TRUE_1 1 + + + /* ------------------- Expression types (LABELS,CONSTANTS,etc) ------------- */ + #define ABSOLUTE_OR_RELATIVE_1 0 /* Don't know type */ + #define ABSOLUTE_VALUE_1 1 /* Absolute expressions */ + #define RELATIVE_VALUE_1 2 /* Relative expressions */ + #define EXTERN_VALUE_1 3 /* An external reference */ + + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/convert.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/convert.c:1.1 *** /dev/null Tue Oct 5 16:08:51 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/convert.c Tue Oct 5 16:08:39 2004 *************** *** 0 **** --- 1,104 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* ============================= convert.c ================================= */ + /* Contains routines that convert one thing to another. Most of the routines */ + /* deal with converting a number to a string of that number in some base, or */ + /* converting a string (assuming some base) into an integer. Basically */ + /* just a file of miscellaneous 'useful' routines. */ + #include + #include + #include + #include "boolean.h" + #include "constants.h" + + /* ----------------------------- eoln -------------------------------------- */ + /* true if CH is the End Of LiNe character, otherwise false. */ + BOOLEAN eoln(char CH) + { + return (CH == '\0'); + } + + /* ------------------------ CHAR_TO_DIGIT ---------------------------------- */ + /* Convert a character (CH) into its integer value give base NUM_BASE. Return*/ + /* -1 if it is not a valid digit in that base. */ + int CHAR_TO_DIGIT(char CH,int NUM_BASE) + { + int DIGIT = -1; + if ( (CH >= '0') && (CH <= '9') ) DIGIT = (int) (CH - '0'); + if ( (CH >= 'A') && (CH <= 'Z') ) DIGIT = ((int) (CH - 'A'))+10; + if (DIGIT >= NUM_BASE) DIGIT = -1; + return DIGIT; + } + + + /* ------------------------- NUM_TO_STR ------------------------------------ */ + /* Put into STR the string with LEN digits that represents the number NUM */ + /* in base BASE (eg. NUM_TO_STR(10,16,3,STR) puts "00A" in STR). */ + void NUM_TO_STR(int NUM,int BASE,int LEN,char *STR) + { + int I; /* loop counter */ + int DIGIT; /* one digit in base specified of NUM */ + + STR[LEN] = '\0'; + for (I=(LEN-1); I>=0; I--) { + DIGIT = NUM - (NUM/BASE) * BASE; + NUM /= BASE; + if ((DIGIT >= 0) && (DIGIT <= 9)) + STR[I] = (char) DIGIT + '0'; + else STR[I] = (char) (DIGIT-10) + 'A'; + } + if (NUM != 0) + (void) printf("NUM_TO_STR called illegally.\n"); + } + + /* ------------------------------ GET_NUM ---------------------------------- */ + /* CURRENT_CHAR points to a string. Starting with the character */ + /* **CURRENT_CHAR and get the biggest possible integer in BASE NUM_BASE. If */ + /* that number is too large/small to fit in BITS bits (2's complement), */ + /* Put an error message into ERROR_REC_BUF. Returns 0 if this or any error is*/ + /* detected, otherwise it returns the integer representation of the number. */ + /* NOTE: If number is to large/small this routine stops as soon as it */ + /* realizes this w/o (with out) looking at the rest of the input. */ + int GET_NUM(char **CURRENT_CHAR,int BITS,int NUM_BASE,BOOLEAN *ERROR) + { + int CONVERT = 0; /* CONVERT is the converted integer of the */ + /* string */ + int MAX_UNSIGNED_INT; /* MAX_UNSIGNED_INT = 2^BITS */ + /* - Biggest biggest number + 1 */ + /* (w/o sign) that fits */ + int DIGIT; /* One digit of the number. */ + + MAX_UNSIGNED_INT = (int) pow(2.0,BITS*1.0); + + /* ----------------------------- Get the biggest [legal] number you can */ + while ( ( (DIGIT = CHAR_TO_DIGIT(**CURRENT_CHAR,NUM_BASE)) != -1) && + !eoln(**CURRENT_CHAR) ) { + if (CONVERT <= MAX_UNSIGNED_INT) + CONVERT = CONVERT*NUM_BASE + DIGIT; + (*CURRENT_CHAR) ++; + } + + if ( (CONVERT > (MAX_UNSIGNED_INT - 1)) || + (!eoln(**CURRENT_CHAR)) ) (*ERROR) = TRUE_1; + + return CONVERT; + } + + /* -------------------------------- STR_TO_NUM ----------------------------- */ + /* Convert the first DIGITS characters of STR to an integer of base BASE. */ + void STR_TO_NUM(char *STR,int DIGITS,int BASE,int *NUM,BOOLEAN *ERROR) + { + int I; + int ONE_DIGIT; + BOOLEAN LOCAL_ERROR = FALSE_1; + + (*NUM) = 0; + for (I = 0; ((I < DIGITS) && !LOCAL_ERROR); I ++) + if ( (ONE_DIGIT = CHAR_TO_DIGIT(STR[I],BASE)) == -1) + LOCAL_ERROR = TRUE_1; /* Not a valid number. */ + else + (*NUM) = (*NUM)*BASE + ONE_DIGIT; + + if (LOCAL_ERROR) (*ERROR) = TRUE_1; + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/convert.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/convert.h:1.1 *** /dev/null Tue Oct 5 16:08:51 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/convert.h Tue Oct 5 16:08:39 2004 *************** *** 0 **** --- 1,60 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* =============================== convert.h =============================== */ + /* Contains routines that convert one thing to another. Most of the routines */ + /* deal with converting a number to a string of that number in some base, or */ + /* converting a string (assuming some base) into an integer. Basically */ + /* just a file of miscellaneous 'useful' routines. */ + + /* ----------------------------- eoln -------------------------------------- */ + /* true if CH is the End Of LiNe character, otherwise false. */ + /* 1 parameter: */ + /* 1) char CH; Character in question. */ + extern int eoln(); + + /* ------------------------ CHAR_TO_DIGIT ---------------------------------- */ + /* 2 parameters: */ + /* 1) char CH; character to convert */ + /* 2) int NUM_BASE; base of number */ + /* Convert a character (CH) into its integer value give base NUM_BASE. Return*/ + /* -1 if it is not a valid digit in that base. */ + extern int CHAR_TO_DIGIT(); + + /* ------------------------- NUM_TO_STR ------------------------------------ */ + /* 4 parameters: */ + /* 1) int NUM; Number to convert */ + /* 2) int BASE; Base to convert into */ + /* 3) int LEN; Number of digits in final string */ + /* 4) char *STR; where to put it. */ + /* Put into STR the string with LEN digits that represents the number NUM */ + /* in base BASE (eg. NUM_TO_STR(10,16,3,STR) puts "00A" in STR). */ + extern void NUM_TO_STR(); + + /* ------------------------------ GET_NUM ---------------------------------- */ + /* 4 parameters: */ + /* 1) char **CURRENT_CHAR; pointer to start of string to interpret */ + /* as an integer (in NUM_BASE) */ + /* 2) int BITS; Number must fit in this may bits 2's */ + /* complement. */ + /* 3) int NUM_BASE; Base the number is in. */ + /* 4) BOOLEAN *ERROR; Was an error detected. */ + /* CURRENT_CHAR points to a string. Starting with the character */ + /* **CURRENT_CHAR and get the biggest possible integer in BASE NUM_BASE. If */ + /* that number is too large/small to fit in BITS bits (2's complement), */ + /* Put an error message into ERROR_REC_BUF. Returns 0 if this or any error is*/ + /* detected, otherwise it returns the integer representation of the number. */ + /* NOTE: If number is to large/small this routine stops as soon as it */ + /* realizes this w/o (with out) looking at the rest of the input. */ + extern int GET_NUM(); + + /* -------------------------------- STR_TO_NUM ----------------------------- */ + /* Convert the first DIGITS characters of STR to an integer of base BASE. */ + /* 5 paramaters: */ + /* 1) char *STR; STRing to convert. */ + /* 2) int DIGITS; number of DIGITS of string to convert. */ + /* 3) int BASE; BASE of the number. */ + /* 4) int *NUM; Place to return the result */ + /* 5) BOOLEAN *ERROR; Has an error been detected. */ + extern void STR_TO_NUM(); + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/debugger.c diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/debugger.c:1.1 *** /dev/null Tue Oct 5 16:08:51 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/debugger.c Tue Oct 5 16:08:39 2004 *************** *** 0 **** --- 1,806 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + + /* =============================== debugger.c =============================== */ + /* Drives the whole simulatation/debugging process. Contains the debugging */ + /* Routines and calls the simulation routines (else where defined). */ + #include + #include "memory.h" + #include "boolean.h" + #include "constants.h" + #include "sym_tab.h" + #include "sim_debug.h" + #include "machine.h" + #include "stringI.h" + /* ---------------------------------- Globals ------------------------------ */ + /* MAIN_ROUTINE Name of (program) module declared with */ + /* a START (main routine). */ + char MAIN_ROUTINE[LABEL_SIZE_1+1]; + + /* START_ADDRESS Location where execution begins */ + int START_ADDRESS = 0; + + /* SYM_TAB The symbol table */ + SYMBOL_TABLE SYM_TAB; + + /* RETURN_STATUS Status of machine when control returned*/ + int RETURN_STATUS = HALT_1; /* to debugger. */ + + /* TYPE_OUT_MODE Remembers the type out mode */ + char TYPE_OUT_MODE[6] = "Hex"; + + /* ----------------------------- Non-Globals ------------------------------- */ + #define MAX_NUM_BREAK_POINTS 16 + int BREAK_POINTS[MAX_NUM_BREAK_POINTS+1]; + int SORTED_BREAK_POINTS[MAX_NUM_BREAK_POINTS+1]; + int NUM_BREAK_POINTS = 0; + BOOLEAN TRACE = FALSE_1; + + /* ---------------------------- Procedures --------------------------------- */ + + extern int CHAR_TO_DIGIT(char CH,int NUM_BASE); + + /* -------------------------- IS_PREFIX_TO (local) ------------------------- */ + /* Returns TRUE iff PREFIX is a prefix of WORD */ + BOOLEAN IS_PREFIX_TO(char *PREFIX,char *WORD) + { + int COUNT; + int LEN; + + if ((LEN = strlen(PREFIX)) > strlen(WORD)) return FALSE_1; + for (COUNT=0; COUNT < LEN; COUNT ++) + if (PREFIX[COUNT] != WORD[COUNT]) return FALSE_1; + return TRUE_1; + } + + /* ---------------------------- REMOVE_WS (local) ------------------------- */ + /* Line is a pointer to a string. Changes LINE to point to the string that */ + /* starts at the first non-blank/tab character in *LINE. */ + void REMOVE_WS(char **LINE) + { + /* Skip SPACEs and TABs */ + while (((**LINE) == ' ') || ((**LINE) == ' ')) + (*LINE) ++; + } + + /* ------ Different types of things need to type into the debugger. */ + #define ADDRESS_0 0 + #define ADDR_REG_0 1 + #define NUMBER_0 2 + #define VALUE_0 3 + /* ----------------------------- TYPE_IN (local) --------------------------- */ + /* Return a value specified by a type in mode. Assumes: */ + /* No $ prefix Hexidecimal input */ + /* $D prefix Decimal input */ + /* $C prefix Character input. */ + /* $S prefix Address of a LABEL returned. */ + int TYPE_IN(char **COMMAND,BOOLEAN *LEGAL,int RESULT_TYPE) + { + int VALUE = 0; + int LOOP; + + (*LEGAL) = TRUE_1; + REMOVE_WS(COMMAND); + if ( (**COMMAND) == '$') + { + (*COMMAND) ++; + switch (**COMMAND) { + /* -------------------------------- $D prefix ------------------------------ */ + case 'D': + (*COMMAND) ++; + if (CHAR_TO_DIGIT((**COMMAND),10) == -1) { + (void) printf("Expected an decimal, found '%s'. Ignoring command.\n", + *COMMAND); + (*LEGAL) = FALSE_1; + } else { + while (CHAR_TO_DIGIT((**COMMAND),10) != -1) { + VALUE = VALUE * 10 + CHAR_TO_DIGIT((**COMMAND),10); + (*COMMAND) ++; + } + } + break; + + /* -------------------------------- $C prefix ------------------------------ */ + case 'C': + if (RESULT_TYPE != VALUE_0) (*LEGAL) = FALSE_1; + else { + (*COMMAND) ++; + VALUE = (int) **COMMAND; + if ( (**COMMAND != '\0')) (*COMMAND) ++; + } + break; + + /* -------------------------------- $S prefix ------------------------------ */ + case 'S': + if (RESULT_TYPE == NUMBER_0) (*LEGAL) = FALSE_1; + else { + (*COMMAND) ++; + REMOVE_WS(COMMAND); + if (!( ((**COMMAND) >= 'A') && ((**COMMAND) <= 'Z'))) { + (void) printf( + "Expected an identifier, found '%s'. Ignoring command.\n", + *COMMAND); + (*LEGAL) = FALSE_1; + return 0; + } else { + char SYMBOL[LABEL_SIZE_1+1]; + struct SYMBOL_TABLE_ENTRY *SYMB; + + for (LOOP=0; ( (LOOP < LABEL_SIZE_1) && + ( ((**COMMAND) >= 'A') && ((**COMMAND) <= 'Z'))); + LOOP ++) { + SYMBOL[LOOP] = **COMMAND; + (*COMMAND) ++; + } + for (;LOOP ADDRESS) || (MEM_SIZE_1 <= ADDRESS+2)) + PRINT_CONSTANT("",ADDRESS," is a legal memory [word] address.\n"); + else { + /* --------------------- if '=' then a store command */ + if ((*COMMAND) == '=') { + COMMAND++; + VALUE = TYPE_IN(&COMMAND,&NO_ERROR,VALUE_0); + if (!NO_ERROR) return; + REMOVE_WS(&COMMAND); + STORE = TRUE_1; + } + + if ((*COMMAND) != '\0') + (void) printf( + "Expected end of statement, found '%s'. Ignoring command.\n" + ,COMMAND); + else { + + (*END) = '\0'; + /* ------------ Take the appropriate action (STORE/EXAMINE) */ + if (STORE) { + REGISTER[ADDRESS] = VALUE; + MEMORY[ADDRESS] = VALUE/(256*256); + MEMORY[ADDRESS+1] = (VALUE - INT(MEMORY[ADDRESS])*256*256)/256; + MEMORY[ADDRESS+2] = (VALUE - INT(MEMORY[ADDRESS+1])*256); + (void) printf("Set "); + } + VALUE = ((INT(MEMORY[ADDRESS])*256 + INT(MEMORY[ADDRESS+1]))*256+ + INT(MEMORY[ADDRESS+2])); + (void) printf("Location %s = ",START); + if (TYPE_OUT_MODE[0] != 'I') + PRINT_ADDRESS("",VALUE,".\n"); + else { + (void) printf("\n"); + PRINT_INSTRUCTION(ADDRESS,TRUE_1,&VALUE); + } + } + } + } + } + + /* ---------------------------- LIST_BP (local) ---------------------------- */ + /* DEBUGGER COMMAND. */ + /* Print out all the currently set break points. */ + void LIST_BP(char *COMMAND,BOOLEAN *LEGAL) + { + int COUNT; /* A loop counter. */ + + REMOVE_WS(&COMMAND); + (*LEGAL) = TRUE_1; + + if ((*COMMAND) != '\0') + (void) printf("Expected end of statement, found '%s'. Ignoring command.\n" + ,COMMAND); + else + if (NUM_BREAK_POINTS == 0) + (void) printf("No break points set.\n"); + else for (COUNT=0;COUNT ADDR) || (MEM_SIZE_1 <= ADDR)) + PRINT_CONSTANT( + "Address specified ",ADDR," out of range. No break point set.\n"); + else if (NUM_BREAK_POINTS == MAX_NUM_BREAK_POINTS) + PRINT_CONSTANT("All ",MAX_NUM_BREAK_POINTS," breakpoints are in use.\n"); + else if ((*COMMAND) != '\0') + (void) printf("Expected end of statement, found '%s'. Ignoring command.\n" + ,COMMAND); + else { + for (OPEN_SPOT=0;BREAK_POINTS[OPEN_SPOT] != -1; OPEN_SPOT++); + BREAK_POINTS[OPEN_SPOT] = ADDR; + + for (COUNT=NUM_BREAK_POINTS; + ((BREAK_POINTS[SORTED_BREAK_POINTS[COUNT]] > ADDR) && + (COUNT > 0)); + COUNT --) + SORTED_BREAK_POINTS[COUNT+1] = SORTED_BREAK_POINTS[COUNT]; + SORTED_BREAK_POINTS[COUNT+1] = OPEN_SPOT; + NUM_BREAK_POINTS ++; + PRINT_CONSTANT("Set B",OPEN_SPOT,"= "); + PRINT_ADDRESS("",BREAK_POINTS[OPEN_SPOT],"\n"); + } + } + + /* ----------------------------- RESET (local) ----------------------------- */ + /* DEBUGGER COMMAND. */ + /* Remove the specified break point. */ + void RESET_BP(char *COMMAND,BOOLEAN *LEGAL) + { + BOOLEAN NO_ERROR; /* TRUE iff NO_ERROR has been found. */ + int NUM; /* NUM of the break point to remove. */ + int BP; /* Loop counter, steps through the break points*/ + + (*LEGAL) = TRUE_1; + NUM = TYPE_IN(&COMMAND,&NO_ERROR,NUMBER_0); + REMOVE_WS(&COMMAND); + if (NO_ERROR) + if ( (0 > NUM) || (NUM_BREAK_POINTS <= NUM)) { + PRINT_CONSTANT("",NUM," is not a legal break point.\n"); + PRINT_CONSTANT("Expected a number 0 - ",MAX_NUM_BREAK_POINTS, + ". Command ignored.\n"); + } + else if ((*COMMAND) != '\0') + (void) printf("Expected end of statement, found '%s'. Ignoring command.\n" + ,COMMAND); + else + if (BREAK_POINTS[NUM] == -1) + PRINT_CONSTANT("Break point ",NUM," is not set. Command ignored.\n"); + else { + for (BP=1; + ((SORTED_BREAK_POINTS[BP] != NUM) && (BP <= NUM_BREAK_POINTS)); + BP++); + BREAK_POINTS[NUM] = -1; + for (;BP <= NUM_BREAK_POINTS; BP ++) + SORTED_BREAK_POINTS[BP] = SORTED_BREAK_POINTS[BP+1]; + NUM_BREAK_POINTS --; + PRINT_CONSTANT("Removed break point ",NUM,".\n"); + } + } + + /* ------------------------------ AT_BREAK_POINT (local) ------------------- */ + /* returns TRUE iff PC points to an instruction that has a byte in it that */ + /* has been set as a break point. */ + BOOLEAN AT_BREAK_POINT(void) + { + /* Binary Searches the sorted array of break_points for the breakpoint */ + int MID; + int HIGH; + int LOW = 1; + int RANGE; /* How many bytes the instruction is */ + + if (NUM_BREAK_POINTS == 0) return FALSE_1; + HIGH = NUM_BREAK_POINTS; + PRINT_INSTRUCTION(PC_0,FALSE_1,&RANGE); + do { + MID = (LOW + HIGH)/2; + if ((BREAK_POINTS[SORTED_BREAK_POINTS[MID]] >= PC_0) && + (BREAK_POINTS[SORTED_BREAK_POINTS[MID]] <= PC_0 + RANGE - 1)) + return TRUE_1; + if (BREAK_POINTS[SORTED_BREAK_POINTS[MID]] <= PC_0) + LOW = MID + 1; + else HIGH = MID - 1; + } while (LOW <= HIGH); + return FALSE_1; + } + + /* ---------------------------- RUN_IT (local) ----------------------------- */ + /* DEBUGGER COMMAND. */ + /* Set up the machine for execution of the proceedure and keep executing */ + /* instructions until it stops or hits a break point. */ + void RUN_IT(char *COMMAND,BOOLEAN *LEGAL) + { + REMOVE_WS(&COMMAND); + (*LEGAL) = TRUE_1; + + if ((*COMMAND) != '\0') + (void) printf("Expected end of statement, found '%s'. Ignoring command.\n" + ,COMMAND); + else { + int DONT_CARE; + + RETURN_STATUS = EXECUTING_1; + L_0 = RETURN_TO_OS_1; + PC_0 = START_ADDRESS; + RESET_DEVICES(); + + SW_0 = 61440; /* 00000001111000000000000 binary = 61440 decimal */ + /* User mode, Running, PID = 0, CC = 0, MASK = 1111, ICODE = 0 */ + if (TRACE) PRINT_INSTRUCTION(PC_0,TRUE_1,&DONT_CARE); + while ((RETURN_STATUS == EXECUTING_1) && !AT_BREAK_POINT()) { + EXEC(TRUE_1,TRACE); + if ((TRACE) && (RETURN_STATUS == EXECUTING_1)) { + (void) printf("\n"); + PRINT_INSTRUCTION(PC_0,TRUE_1,&DONT_CARE); + } + } + if (RETURN_STATUS == EXECUTING_1) + PRINT_ADDRESS("Break point encountered at ",PC_0,".\n"); + } + } + + /* ---------------------------- PROCEED (local) ---------------------------- */ + /* DEBUGGER COMMAND. */ + /* Continue execution a program from a break point until the program */ + /* terminates or another break point is found. */ + void PROCEED(char *COMMAND,BOOLEAN *LEGAL) + { + int DONT_CARE; + + REMOVE_WS(&COMMAND); + (*LEGAL) = TRUE_1; + + if ((*COMMAND) != '\0') + (void) printf("Expected end of statement, found '%s'. Ignoring command.\n" + ,COMMAND); + else { + + if (RETURN_STATUS != EXECUTING_1) + (void) printf("Can not continue. Instruction ignored.\n"); + else + do { + EXEC(TRUE_1,TRACE); + if ((TRACE) && (RETURN_STATUS == EXECUTING_1)) { + (void) printf("\n"); + PRINT_INSTRUCTION(PC_0,TRUE_1,&DONT_CARE); + } + } while ((RETURN_STATUS == EXECUTING_1) && !AT_BREAK_POINT()); + + if (RETURN_STATUS == EXECUTING_1) + PRINT_ADDRESS("Break point encountered at ",PC_0,".\n"); + } + } + + /* ---------------------------- EXAMINE (local) ---------------------------- */ + /* DEBUGGER COMMAND. */ + /* Execute on instruction, printing the result and the next instruction to */ + /* execute. */ + void STEP(char *COMMAND,BOOLEAN *LEGAL) + { + int DONT_CARE; + + REMOVE_WS(&COMMAND); + (*LEGAL) = TRUE_1; + + if ((*COMMAND) != '\0') + (void) printf("Expected end of statement, found '%s'. Ignoring command.\n" + ,COMMAND); + else { + + if (RETURN_STATUS != EXECUTING_1) + (void) printf("Can not continue. Instruction ignored.\n"); + else { + EXEC(TRUE_1,TRUE_1); + (void) printf("\n"); + if (RETURN_STATUS == EXECUTING_1) + PRINT_INSTRUCTION(PC_0,TRUE_1,&DONT_CARE); + } + + } + } + + /* ------------------------------- HELP (local) ---------------------------- */ + /* DEBUGGER COMMAND. */ + /* Prints out the debuggers help message. */ + void HELP(char *COMMAND,BOOLEAN *LEGAL) + { + REMOVE_WS(&COMMAND); + (*LEGAL) = TRUE_1; + if ((*COMMAND) != '\0') + (void) printf("Expected end of statement, found '%s'. Ignoring command.\n" + ,COMMAND); + else { + (void) printf("List of commands:\n"); + (void) printf(" Short Long Function\n\n"); + (void) printf(" B BREAK Set break point at .\n"); + (void) printf(" B? BREAK? List out the break points.\n"); + (void) printf(" H HELP Displays this table.\n"); + (void) printf( + " L LOC Examines contents of memory and registers.\n"); + (void) printf( + " L= LOC= Examines contents of memory and registers.\n"); + (void) printf(" M MODE Set type out mode.\n"); + (void) printf(" P PROCEED Proceed from break point.\n"); + (void) printf(" Q QUIT Exit Debugger.\n"); + (void) printf( + " R RUN Start execution at entry point.\n"); + (void) printf(" RB RESET Remve break point .\n"); + (void) printf(" S STEP Execute one instruction.\n"); + (void) printf(" T TRACE Trace the execution.\n"); + (void) printf( + " U UNTRACE Stop tracing the execution.\n"); + (void) printf("\n"); + (void) printf(" = memory address or label.\n"); + (void) printf(" = memory address, label or register.\n"); + (void) printf( + " = H (hexidecimal), D (decimal), or I (instruction).\n"); + (void) printf( + " = hexidecimal number, decimal number, or 1 character.\n\n"); + } + } + + /* ---------------------------- EXAMINE (local) ---------------------------- */ + /* DEBUGGER COMMAND. */ + /* Tells the debugger that the user wish to terminate the debugging session. */ + void QUIT(char *COMMAND,BOOLEAN *LEGAL) + { + (*LEGAL) = TRUE_1; + REMOVE_WS(&COMMAND); + if ((*COMMAND) != '\0') + (void) printf("Expected end of statement, found '%s'. Ignoring command.\n" + ,COMMAND); + else { + RETURN_STATUS = QUIT_1; + } + } + + /* ---------------------------- TRACE_P (local) ---------------------------- */ + /* DEBUGGER COMMAND. */ + /* Turns on the tracing mode. */ + void TRACE_P(char *COMMAND,BOOLEAN *LEGAL) + { + (*LEGAL) = TRUE_1; + REMOVE_WS(&COMMAND); + if ((*COMMAND) != '\0') + (void) printf("Expected end of statement, found '%s'. Ignoring command.\n" + ,COMMAND); + else + if (TRACE) (void) printf("Trace is already on.\n"); + else { + TRACE = TRUE_1; + (void) printf("Trace is now on.\n"); + } + } + + /* --------------------------- UNTRACE_P (local) --------------------------- */ + /* DEBUGGER COMMAND. */ + /* Turns off tracing mode. */ + void UNTRACE(char *COMMAND,BOOLEAN *LEGAL) + { + (*LEGAL) = TRUE_1; + REMOVE_WS(&COMMAND); + if ((*COMMAND) != '\0') + (void) printf("Expected end of statement, found '%s'. Ignoring command.\n" + ,COMMAND); + else + if (!TRACE) (void) printf("Trace is already off.\n"); + else { + TRACE = FALSE_1; + (void) printf("Trace is now off.\n"); + } + } + + /* ------------------------------ MODE (local) ----------------------------- */ + /* DEBUGGER COMMAND. */ + /* Set the type out mode [(H)exidecimal, (D)ecimal, (I)nstruction] */ + void MODE(char *COMMAND,BOOLEAN *LEGAL) + { + (*LEGAL) = TRUE_1; + REMOVE_WS(&COMMAND); + if (*COMMAND == '\0') + (void) printf("Unexpected end of command. Ignoring command.\n"); + else { + if (*(COMMAND+1) == '\0') + switch (*COMMAND) { + case 'H': + (void) strcpy(TYPE_OUT_MODE,"Hex"); + return; + break; + case 'D': + (void) strcpy(TYPE_OUT_MODE,"Dec"); + return; + break; + case 'I': + (void) strcpy(TYPE_OUT_MODE,"Instr"); + return; + break; + default: ; + } + + (void) printf( + "Expected valid mode (H,D, or I). Found %s. Ignoring command.\n", + COMMAND); + } + } + + /* ---------------------- CAPITALIZE_STRING -------------------------------- */ + /* Make all lower case letters in the string STR upper case letters */ + void CAPITALIZE_STRING(char STR[]) + { + int I; + for (I=0; I<= (strlen(STR)); I++) + if ((STR[I] >= 'a') && (STR[I] <= 'z')) + STR[I] = STR[I] - 'a' + 'A'; + } + + + #define STEP0 1 + #define SET_BP0 2 + #define EXAMINE0 3 + #define RESET_BP0 4 + #define RUN_IT0 5 + #define HELP0 6 + #define MODE0 7 + #define PROCEED0 8 + #define TRACE_P0 9 + #define UNTRACE0 10 + #define QUIT0 11 + + /* ~~~~~~~~~~~~~~~~~~~~~~ Table with the debugger commands */ + #define COM_TAB_SIZE_1 11 + struct COMMAND_TYPE { + char *SHORT; /* Short version of command. */ + char *LONG; /* Long version of the command. */ + int FUNCTION; + } COMMANDS[COM_TAB_SIZE_1] = + {{"S","STEP",STEP0}, + {"B","BREAK",SET_BP0}, + {"L","LOC",EXAMINE0}, + {"RB","RESET",RESET_BP0}, + {"R","RUN",RUN_IT0}, + {"H","HELP",HELP0}, + {"M","MODE",MODE0}, + {"P","PROCEED",PROCEED0}, + {"T","TRACE",TRACE_P0}, + {"U","UNTRACE",UNTRACE0}, + {"Q","QUIT",QUIT0}}; + + void CALL_FUNCTION(int FUNC,char *COMMAND,BOOLEAN *LEGAL) + { + switch(FUNC) { + case STEP0: STEP(COMMAND,LEGAL); + break; + case SET_BP0: SET_BP(COMMAND,LEGAL); + break; + case EXAMINE0: EXAMINE(COMMAND,LEGAL); + break; + case RESET_BP0: RESET_BP(COMMAND,LEGAL); + break; + case RUN_IT0: RUN_IT(COMMAND,LEGAL); + break; + case HELP0: HELP(COMMAND,LEGAL); + break; + case MODE0: MODE(COMMAND,LEGAL); + break; + case PROCEED0: PROCEED(COMMAND,LEGAL); + break; + case TRACE_P0: TRACE_P(COMMAND,LEGAL); + break; + case UNTRACE0: UNTRACE(COMMAND,LEGAL); + break; + case QUIT0: QUIT(COMMAND,LEGAL); + break; + } + } + /* -------------------------------- DEBUGGER ------------------------------- */ + /* Drives the entire simulatation/debugging process. */ + void DEBUGGER(BOOLEAN DEBUG_MODE) + { + char *COMMAND; /* The debugging command. */ + BOOLEAN LEGAL_COMMAND; /* Is this a recognized command? */ + int COUNT; /* Loop counter. */ + + for (COUNT=0; COUNT <= MAX_NUM_BREAK_POINTS; COUNT ++) + BREAK_POINTS[COUNT] = -1; + + if (!DEBUG_MODE) { + /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ No Debugging, just execute it */ + RETURN_STATUS = EXECUTING_1; + L_0 = RETURN_TO_OS_1; + PC_0 = START_ADDRESS; + + SW_0 = 61440; /* 00000001111000000000000 binary = 61440 decimal */ + /* User mode, Running, PID = 0, CC = 0, MASK = 1111, ICODE = 0 */ + EXEC(FALSE_1,FALSE_1); + } else + /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Debug the program. */ + while (RETURN_STATUS != QUIT_1) { + LEGAL_COMMAND = FALSE_1; + (void) printf("%s> ",TYPE_OUT_MODE); + GET_LINE(&COMMAND,stdin); + REMOVE_WS(&COMMAND); + if ((*COMMAND) != '\0') { + CAPITALIZE_STRING(COMMAND); + + for (COUNT=0; (COUNT < COM_TAB_SIZE_1) && !LEGAL_COMMAND; COUNT++) + if (IS_PREFIX_TO(COMMANDS[COUNT].LONG,COMMAND)) + CALL_FUNCTION(COMMANDS[COUNT].FUNCTION, + &(COMMAND[strlen(COMMANDS[COUNT].LONG)]), + &LEGAL_COMMAND); + else if (IS_PREFIX_TO(COMMANDS[COUNT].SHORT,COMMAND)) + CALL_FUNCTION(COMMANDS[COUNT].FUNCTION, + &(COMMAND[strlen(COMMANDS[COUNT].SHORT)]), + &LEGAL_COMMAND); + + if (!LEGAL_COMMAND) { + (void) printf("'%s' is not a legal command. Ignoring it.\n",COMMAND); + (void) printf("Type HELP for the list of legal commands.\n"); + } + } + if (RETURN_STATUS == ABNORMAL_1) { + int CODE; + + RETURN_STATUS = HALT_1; + CODE = SW_0 - (SW_0/256)*256; + PRINT_CONSTANT("error code =",CODE," "); + switch (CODE) { + case 0: (void) printf("Illegal instruction.\n"); break; + case 1: (void) printf("Privileged instruction in user mode.\n"); break; + case 2: (void) printf("Address out of range.\n"); break; + case 3: (void) printf("Memory-protection violation.\n"); break; + case 4: (void) printf("Aritmetic overflow.\n"); break; + case 10: (void) printf("Page fault.\n"); break; + case 11: (void) printf("Segment fault.\n"); break; + case 12: (void) printf("Segment-protection violation.\n"); break; + case 13: (void) printf("Segment length exceeded.\n"); break; + default: (void) printf("\n"); break; + } + } + } + } Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/debugger.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/debugger.h:1.1 *** /dev/null Tue Oct 5 16:08:51 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/debugger.h Tue Oct 5 16:08:39 2004 *************** *** 0 **** --- 1,31 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /* =============================== debugger.h ============================== */ + /* Drives the whole simulatation/debugging process. Contains the debugging */ + /* Routines and calls the simulation routines (else where defined). */ + #include "sym_tab.h" + /* ---------------------------------- Globals ------------------------------ */ + /* MAIN_ROUTINE Name of (program) module declared with */ + /* a START (main routine). */ + extern char MAIN_ROUTINE[LABEL_SIZE_1+1]; + + /* START_ADDRESS Location where execution begins */ + extern int START_ADDRESS; + + /* SYM_TAB The symbol table */ + extern SYMBOL_TABLE SYM_TAB; + + /* RETURN_STATUS Status of machine when control returned*/ + extern int RETURN_STATUS; /* to debugger. */ + + /* TYPE_OUT_MODE Remembers the type out mode */ + char TYPE_OUT_MODE[6]; + + /* ------------------------------- Procedures ------------------------------ */ + /* -------------------------------- DEBUGGER ------------------------------- */ + /* 1 parameter: */ + /* 1) BOOLEAN DEBUG_MODE; TRUE => Debugging. FALSE => just simulating */ + /* Drives the entire simulatation/debugging process. */ + extern void DEBUGGER (); + Index: llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/define-instr-tab.h diff -c /dev/null llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/define-instr-tab.h:1.1 *** /dev/null Tue Oct 5 16:08:51 2004 --- llvm-test/MultiSource/Benchmarks/Prolangs-C/simulator/define-instr-tab.h Tue Oct 5 16:08:39 2004 *************** *** 0 **** --- 1,127 ---- + /* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Permission to use this code is granted as long as the copyright */ + /* notice remains in place. */ + /*============================ define-instr-tab.h ======================= */ + /* A table for quick (constant time) look up of MNEMONIC, FORMAT, and */ + /* the function that knows what to do with an instruction give its code. */ + + struct INSTR_INFO { + char *MNEMONIC; + int FORMAT; + int FUNCTION; + }; + + + #define LDA_P0 22 + #define LDX_P0 1 + #define LDL_P0 2 + #define STA_P0 3 + #define STX_P0 4 + #define STL_P0 5 + #define ADD_P0 6 + #define SUB_P0 7 + #define MUL_P0 8 + #define DIV_P0 9 + #define COMP_P0 10 + #define TIX_P0 11 + #define JEQ_P0 12 + #define JGT_P0 13 + #define JLT_P0 14 + #define J_P0 15 + #define AND_P0 16 + #define OR_P0 17 + #define JSUB_P0 18 + #define RSUB_P0 19 + #define LDCH_P0 20 + #define STCH_P0 21 + #define NULL0 0 + #define LDB_P0 23 + #define LDS_P0 24 + #define LDT_P0 25 + #define STB_P0 26 + #define STS_P0 27 + #define STT_P0 28 + #define ADDR_P0 29 + #define SUBR_P0 30 + #define MULR_P0 31 + #define DIVR_P0 32 + #define COMPR_P0 33 + #define SHIFTL_P0 34 + #define SHIFTR_P0 35 + #define RMO_P0 36 + #define SVC_P0 37 + #define CLEAR_P0 38 + #define TIXR_P0 39 + #define STI_P0 40 + #define RD_P0 41 + #define WD_P0 42 + #define TD_P0 43 + #define STSW_P0 44 + + + #define INSTR_TAB_SIZE_1 64 + struct INSTR_INFO INSTR[INSTR_TAB_SIZE_1] = + {{"LDA",3,LDA_P0}, /* Opcode = 00 */ + {"LDX",3,LDX_P0}, /* Opcode = 04 */ + {"LDL",3,LDL_P0}, /* Opcode = 08 */ + {"STA",3,STA_P0}, /* Opcode = 0C */ + {"STX",3,STX_P0}, /* Opcode = 10 */ + {"STL",3,STL_P0}, /* Opcode = 14 */ + {"ADD",3,ADD_P0}, /* Opcode = 18 */ + {"SUB",3,SUB_P0}, /* Opcode = 1C */ + {"MUL",3,MUL_P0}, /* Opcode = 20 */ + {"DIV",3,DIV_P0}, /* Opcode = 24 */ + {"COMP",3,COMP_P0}, /* Opcode = 28 */ + {"TIX",3,TIX_P0}, /* Opcode = 2C */ + {"JEQ",3,JEQ_P0}, /* Opcode = 30 */ + {"JGT",3,JGT_P0}, /* Opcode = 34 */ + {"JLT",3,JLT_P0}, /* Opcode = 38 */ + {"J",3,J_P0}, /* Opcode = 3C */ + {"AND",3,AND_P0}, /* Opcode = 40 */ + {"OR",3,OR_P0}, /* Opcode = 44 */ + {"JSUB",3,JSUB_P0}, /* Opcode = 48 */ + {"RSUB",3,RSUB_P0}, /* Opcode = 4C */ + {"LDCH",3,LDCH_P0}, /* Opcode = 50 */ + {"STCH",3,STCH_P0}, /* Opcode = 54 */ + {"ADDF",3,NULL0}, /* Opcode = 58 */ + {"SUBF",3,NULL0}, /* Opcode = 5C */ + {"MULF",3,NULL0}, /* Opcode = 60 */ + {"DIVF",3,NULL0}, /* Opcode = 64 */ + {"LDB",3,LDB_P0}, /* Opcode = 68 */ + {"LDS",3,LDS_P0}, /* Opcode = 6C */ + {"LDF",3,NULL0}, /* Opcode = 70 */ + {"LDT",3,LDT_P0}, /* Opcode = 74 */ + {"STB",3,STB_P0}, /* Opcode = 78 */ + {"STS",3,STS_P0}, /* Opcode = 7C */ + {"STF",3,NULL0}, /* Opcode = 80 */ + {"STT",3,STT_P0}, /* Opcode = 84 */ + {"COMPF",3,NULL0}, /* Opcode = 88 */ + {"UNDEF",1,NULL0}, /* Opcode = 8C */ + {"ADDR",2,ADDR_P0}, /* Opcode = 90 */ + {"SUBR",2,SUBR_P0}, /* Opcode = 94 */ + {"MULR",2,MULR_P0}, /* Opcode = 98 */ + {"DIVR",2,DIVR_P0}, /* Opcode = 9C */ + {"COMPR",2,COMPR_P0}, /* Opcode = A0 */ + {"SHIFTL",2,SHIFTL_P0}, /* Opcode = A4 */ + {"SHIFTR",2,SHIFTR_P0}, /* Opcode = A8 */ + {"RMO",2,RMO_P0}, /* Opcode = AC */ + {"SVC",2,SVC_P0}, /* Opcode = B0 */ + {"CLEAR",2,CLEAR_P0}, /* Opcode = B4 */ +