sagexx_ug (1158317), страница 8

Файл №1158317 sagexx_ug (Раздаточные материалы) 8 страницаsagexx_ug (1158317) страница 82019-09-18СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 8)

Typescharacterize the properties of symbols. Because C++ and Fortran 90 have fairly rich type structures,there are many Sage type classes.6.1 SgTypeSgType is the base class for all classes that represent types. As with symbols, types in a leform a list that can be accessed with the function `SgFile::firstType()'. The `next()' functionreturns the type node following `this'. The function `copy()' returns a copy of the type node.Many types are dened in terms of other types. For example, an array type has a base typethat may be a pointer type which has a base type that may be an integer or a class, etc. The`baseType()' function always access the next type in the chain. For the language pC++ there is adummy type called `ElementType' which is used as a \place holder" or parameter for a type that issupplied later. Another function `equivalentToType()' can be used to test to types to see if theyare equivalent.class SgType {public:PTR_TYPE thetype;SgType(int variant);SgType(PTR_TYPE type);intvariant();intid();SgSymbol * symbol();SgType ©();SgType *next();intisTheElementType();intequivalentToType(SgType &type);SgType *internalBaseType();inthasBaseType();SgType *baseType();};SgType is used in the following places in the example programs: see [Restructure - addStuToProgram], page 135 see [Instrument - Fortran Program Transformations], page 140Chapter 6: Types122see [Instrument - isReferenceToClassOfElement], page 148see [Instrument - isReferenceToCollection], page 150see [Instrument - ListCollectionInstances], page 153see hundenedi [Expand Syntax], page hundenedisee [Expand Syntax - isArrayRefOfCollection], page 161see [Expand Syntax - ReplaceWithGetElemPart], page 163see [Expand Syntax - MatchingDummyVar], page 165see [Expand Syntax - InDummyVarTable], page 166see [Expand Syntax - Init], page 166see [Dump Info - classifyStatements], page 170see [Dump Info - doFullType], page 180Member Functions:SgType(int variant)SgType(PTR TYPE type)int variant()int id()SgSymbol * symbol()SgType & copy()SgType * next()int isTheElementType()int equivalentToType(SgType &type)SgType * internalBaseType()int hasBaseType()SgType * baseType()SgType UsageTo illustrate the use of the type table, consider the simple problem of identifying when a variablein a variable reference expression is of a given user dened class.

More specically, givenChapter 6: Types123class myClass;myClass x, y;y = x + 2;then if e is the expression representing the variable reference to x, we would like a functionisVarRefOfClass(e, "myClass") that will return 1 because the class type matches. To do this werst check to see if e is indeed a variable reference. Then, extracting the type of the symbol weshould nd a derived type. From the derived type we can nd the name of the class.int isVarRefOfClass(SgExpression *e, char *classname){SgSymbol *s;SgDerivedType *d;SgClassSymb *cl;SgVarRefExp *exp;if((exp = isSgVarRefExp(e)) == NULL) return 0;s = exp->symbol();if((d = isSgDerivedType(s->type())) == NULL) return 0;if(cl = isSgClassSymb(d->typeName()))if(!strcmp(cl->identifier(), classname))return 1;return 0;}A function of the typeSgSUBCLASS * isSgSUBCLASS( SgBASECLASS *)is provided for each subclass of SgStatement, SgExpression and SgType.

We feel that this mechanism is an eective way to use the strong typing of C++ to reduce errors.6.2 SgArrayTypeRepresents types for arrays, for all languages.The parser gives each array variable its own Array type descriptor object.Variant: T ARRAYFor base class, see Section 6.1 [SgType], page 121.class SgArrayType: public SgType {public:SgArrayType(SgType &base_type);intdimension();SgExpression * sizeInDim(int i);SgType *baseType();voidsetBaseType(SgType &bt);voidaddRange(SgExpression &e);Chapter 6: Types124};SgArrayType is used in the following places in the example programs: see [Restructure - addStuToProgram], page 135 see [Dump Info - doFullType], page 180Member Functions:SgArrayType(SgType &base type)Each array must have a base type which may be any type object.int dimension()SgExpression * sizeInDim(int i)Returns the expression that describes the the shape of the array.

If this expression is a SgSubscriptExpr then it is a Fortran array which has a non-unit starting index and a upper boundindex.SgType * baseType()void setBaseType(SgType &bt)Modies the base type.void addRange(SgExpression &e)Allows a new dimension to be added.6.3 SgClassTypeRepresents C types for structs, types for unions, and types for enums.Represents C++ types for base classes.Represents pC++ types for collections.Represents Fortran types for records.This type is very simple. It contains the standard type information from SgType, a pointer tothe class declaration statement, and a pointer to the symbol that is the rst eld in the structure.Note: derived classes have a dierent type.Variants: T STRUCT, T ENUM, T CLASS, T ENUM, and T COLLECTION.Chapter 6: Types125For base class, see Section 6.1 [SgType], page 121.class SgClassType: public SgType {#if 0// a C struct or Fortran Record, a C++ class, a C Union and a C Enum// and a pC++ collection.

note: derived classes are another type.// this type is very simple. it only contains the standard type// info from SgType and a pointer to the class declaration stmt// and a pointer to the symbol that is the first field in the struct.// variant == T_STRUCT, T_ENUM, T_CLASS, T_ENUM, T_COLLECTIONpublic:// why is struct_decl needed. No appropriate field found.// assumes that first_field has been declared as// FIELD_NAME and the remaining fields have been stringed to it.SgClassType(int variant, char *name, SgStatement &struct_decl,int num_fields, SgSymbol &first_field);SgStatement & structureDecl();SgSymbol *firstFieldSymb();SgSymbol *fieldSymb(int i);intnumberOfFields();};Member Functions:SgClassType(int&rst eld)variant, char *name, SgStatement &struct decl, int num elds, SgSymbolSgStatement & structureDecl()Returns a reference to the source code that denes this structure.SgSymbol * rstFieldSymb()Returns a pointer to the symbol entry for the rst eld.

Symbols for All other elds are chainedto that symbol.SgSymbol * eldSymb(int i)Returns a pointer to the `i'th eld.int numberOfFields()6.4 SgFunctionTypeRepresents types for functions, for all languages.Chapter 6: Types126The important information here is the type of the returned value.Variant: T FUNCTIONFor base class, see Section 6.1 [SgType], page 121.class SgFunctionType: public SgType {#if 0public:SgFunctionType(SgType &return_val_type);SgType & returnedValue();voidchangeReturnedValue(SgType &rv);};Member Functions:SgFunctionType(SgType &return val type)SgType & returnedValue()void changeReturnedValue(SgType &rv)Allows modication of the returned value.6.5 SgDescriptTypeRepresents C unsigned, signed, long, short, extern, static, and register.Represents C++ private, virtual, inline, volatile, const,auto, and friend.Represents Fortran 90 syn, shared, future, and global.This class represents descriptor objects that modify other type objects.

For example, in the Cthe expressionlong volatile int x;long and volatile are modiers and there is a descriptor type whose base type is the real type of x.the modier is an integer with bits set if the modier holds.The modier bits are: BIT SYN, BIT SHARED, BIT PRIVATE, BIT FUTURE, BIT VIRTUAL,BIT INLINE, BIT UNSIGNED, BIT SIGNED, BIT LONG, BIT SHORT, BIT VOLATILE, BIT CONST,BIT TYPEDEF, BIT EXTERN, BIT AUTO, BIT STATIC, BIT REGISTER, and BIT FRIENDVariant: T DESCRIPTChapter 6: Types127For base class, see Section 6.1 [SgType], page 121.class SgDescriptType: public SgType {public:SgDescriptType(SgType &base_type, int bit_flag);intmodifierFlag();void setModifierFlag(int flag);};SgDescriptType is used in the following places in the example programs: see [Dump Info - doFullType], page 180Member Functions:SgDescriptType(SgType &base type, int bit ag)int modierFlag()void setModierFlag(int ag)6.6 SgPointerTypeRepresents C pointer type.Variant: T POINTERThe important information is encoded in the base type, i.e.

the type of thing this pointer canpoint to.For base class, see Section 6.1 [SgType], page 121.class SgPointerType: public SgType {// A pointer type contains only one hany bit of information:// the base type.// variant == T_POINTERpublic:SgPointerType(SgType &base_type);SgType * baseType();intindirection();voidsetIndirection(int);voidsetBaseType(SgType &baseType);};Chapter 6: Types128SgPointerType is used in the following places in the example programs: see [Instrument - isReferenceToCollection], page 150 see [Expand Syntax - ReplaceWithGetElemPart], page 163 see [Expand Syntax - Init], page 166 see [Dump Info - doFullType], page 180Member Functions:SgPointerType(SgType &base type)SgType * baseType()int indirection()void setIndirection(int)void setBaseType(SgType &baseType)Can modify the base type.6.7 SgDerivedTypeRepresents C typedefed types.Represents C++ instance variables.Variants: T DERIVED TYPE, T DERIVED CLASSFor base class, see Section 6.1 [SgType], page 121.class SgDerivedType: public SgType {public:SgDerivedType(SgSymbol &type_name);SgSymbol * typeName();};SgDerivedType is used in the following places in the example programs: see [Instrument - isReferenceToClassOfElement], page 148 see [Dump Info - doFullType], page 180Chapter 6: Types129Member Functions:SgDerivedType(SgSymbol &type name)SgSymbol * typeName()Returns the object of class SgTypeSymb or SgClassSymb to which this type refers.6.8 SgReferenceTypeRepresents C++ reference types.Variant: T REFERENCEFor base class, see Section 6.1 [SgType], page 121.class SgReferenceType: public SgType {// A reference (&xx in c+=) type contains only one hany bit of information:// the base type.// variant == T_REFERENCEpublic:SgReferenceType(SgType &base_type);SgType * baseType();voidsetBaseType(SgType &baseType);};SgReferenceType is used in the following places in the example programs: see [Instrument - isReferenceToCollection], page 150 see [Dump Info - doFullType], page 180Member Functions:SgReferenceType(SgType &base type)SgType * baseType()void setBaseType(SgType &baseType)Chapter 6: Types6.9 SgDerivedClassTypeRepresents C++ types of derived classes.For base class, see Section 6.1 [SgType], page 121.class SgDerivedClassType: public SgType {// variant == T_DERIVED_CLASSpublic:SgDerivedClassType(SgSymbol &type_name);SgSymbol * typeName();};Member Functions:SgDerivedClassType(SgSymbol &type name)SgSymbol * typeName()6.10 SgDerivedCollectionTypeRepresents pC++ collection classes.For example, if we haveCollection DistributedArray {body1} ;class object {body2} ;DistributedArray<object> X;then the type of X is SgDerivedCollectionType.Variant: T DERIVED COLLECTIONFor base class, see Section 6.1 [SgType], page 121.class SgDerivedCollectionType: public SgType {// for example:// Collection DistributedArray {body1} ;// class object {body2} ;// DistributedArray<object> X;// X is of type with variant = T_DERIVED_COLLECTION130Chapter 6: Typespublic:SgType *voidSgSymbol *SgStatement *};131SgDerivedCollectionType(SgSymbol &s, SgType &t);elementClass();setElementClass(SgType &ty);collectionName();createCollectionWithElemType();SgDerivedCollectionType is used in the following places in the example programs: see [Instrument - isReferenceToClassOfElement], page 148 see [Instrument - isReferenceToCollection], page 150 see [Instrument - ListCollectionInstances], page 153 see [Instrument - ListCollectionInvocations], page 153 see [Instrument - CTimingInstrumentSub], page 156 see hundenedi [Expand Syntax], page hundenedi see [Expand Syntax - isArrayRefOfCollection], page 161 see [Expand Syntax - SearchInExpForCollectionArrayRef], page 162 see [Expand Syntax - ReplaceWithGetElemPart], page 163 see [Expand Syntax - Init], page 166 see [Dump Info - doFullType], page 180Member Functions:SgDerivedCollectionType(SgSymbol &s, SgType &t)t is the collection type.SgType * elementClass()Returns the type of the collection element.void setElementClass(SgType &ty)Sets the type of the collection element.SgSymbol * collectionName()Returns the object of class SgClassSymb that is the name of the collection.SgStatement * createCollectionWithElemType()Chapter 7: Labels7 Labels7.1 SgLabelRepresents labels, for all languages.class SgLabel {public:PTR_LABEL thelabel;SgLabel(PTR_LABEL lab);SgLabel(int i);int id();int getLastLabelVal();};Member Functions:SgLabel(PTR LABEL lab)SgLabel(int i)int id()int getLastLabelVal()132Chapter 8: Non-Member Functions1338 Non-Member FunctionsSgType *SgTypeInt(); SgType *SgTypeChar(); SgType *SgTypeFloat(); SgType *SgTypeDouble(); SgType *SgTypeVoid(); SgType *SgTypeBool(); SgType *SgTypeDefault();SgUnaryExp & SgDerefOp(SgExpression &e); SgUnaryExp & SgAddrOp(SgExpression &e);SgUnaryExp & SgUMinusOp(SgExpression &e); SgUnaryExp & SgUPlusOp(SgExpression &e);SgUnaryExp & SgPrePlusPlusOp(SgExpression &e); SgUnaryExp & SgPreMinusMinusOp(SgExpression&e); SgUnaryExp & SgPostPlusPlusOp(SgExpression &e); SgUnaryExp & SgPostMinusMinusOp(SgExpression &e); SgUnaryExp & SgBitCompfOp(SgExpression &e); SgUnaryExp & SgNotOp(SgExpression &e); SgUnaryExp & SgSizeOfOp(SgExpression &e); SgUnaryExp & makeAnUnaryExpression(int code,PTR LLND ll1);Chapter 8: Non-Member Functions134SgValueExp * isSgValueExp(SgExpression *pt); SgKeywordValExp * isSgKeywordValExp(SgExpression*pt); SgCastExp * isSgCastExp(SgExpression *pt); SgDeleteExp * isSgDeleteExp(SgExpression*pt); SgNewExp * isSgNewExp(SgExpression *pt); SgExprIfExp * isSgExprIfExp(SgExpression*pt); SgFunctionCallExp * isSgFunctionCallExp(SgExpression *pt); SgFuncPntrExp * isSgFuncPntrExp(SgExpression *pt); SgExprListExp * isSgExprListExp(SgExpression *pt); SgRefExp *isSgRefExp (SgExpression *pt); SgVarRefExp * isSgVarRefExp (SgExpression *pt); SgThisExp *isSgThisExp (SgExpression *pt); SgArrayRefExp * isSgArrayRefExp (SgExpression *pt); SgPntrArrRefExp * isSgPntrArrRefExp(SgExpression *pt); SgPointerDerefExp * isSgPointerDerefExp(SgExpression *pt); SgRecordRefExp * isSgRecordRefExp (SgExpression *pt); SgStructConstExp* isSgStructConstExp (SgExpression *pt); SgConstExp* isSgConstExp (SgExpression *pt);SgVecConstExp * isSgVecConstExp (SgExpression *pt); SgInitListExp * isSgInitListExp (SgExpression *pt); SgObjectListExp * isSgObjectListExp (SgExpression *pt); SgAttributeExp *isSgAttributeExp (SgExpression *pt); SgKeywordArgExp * isSgKeywordArgExp (SgExpression*pt); SgSubscriptExp* isSgSubscriptExp (SgExpression *pt); SgUseOnlyExp * isSgUseOnlyExp(SgExpression *pt); SgUseRenameExp * isSgUseRenameExp (SgExpression *pt); SgSpecPairExp* isSgSpecPairExp (SgExpression *pt); SgIOAccessExp * isSgIOAccessExp (SgExpression *pt);SgImplicitTypeExp * isSgImplicitTypeExp (SgExpression *pt); SgTypeExp * isSgTypeExp (SgExpression *pt); SgSeqExp * isSgSeqExp (SgExpression *pt); SgStringLengthExp * isSgStringLengthExp (SgExpression *pt); SgDefaultExp * isSgDefaultExp (SgExpression *pt); SgLabelRefExp *isSgLabelRefExp (SgExpression *pt); SgProgHedrStmt * isSgProgHedrStmt (SgStatement *pt);SgProcHedrStmt * isSgProcHedrStmt (SgStatement *pt); SgFuncHedrStmt * isSgFuncHedrStmt(SgStatement *pt); SgClassStmt * isSgClassStmt (SgStatement *pt); SgStructStmt * isSgStructStmt (SgStatement *pt); SgUnionStmt * isSgUnionStmt (SgStatement *pt); SgEnumStmt *isSgEnumStmt (SgStatement *pt); SgCollectionStmt * isSgCollectionStmt (SgStatement *pt); SgBasicBlockStmt * isSgBasicBlockStmt (SgStatement *pt); SgForStmt * isSgForStmt (SgStatement*pt); SgWhileStmt * isSgWhileStmt (SgStatement *pt); SgDoWhileStmt * isSgDoWhileStmt(SgStatement *pt); SgLogIfStmt * isSgLogIfStmt (SgStatement *pt); SgIfStmt * isSgIfStmt(SgStatement *pt); SgArithIfStmt * isSgArithIfStmt (SgStatement *pt); SgWhereStmt * isSgWhereStmt (SgStatement *pt); SgWhereBlockStmt * isSgWhereBlockStmt (SgStatement *pt);SgSwitchStmt * isSgSwitchStmt (SgStatement *pt); SgCaseOptionStmt * isSgCaseOptionStmt(SgStatement *pt); SgExecutableStatement * isSgExecutableStatement (SgStatement *pt); SgAssignStmt * isSgAssignStmt (SgStatement *pt); SgCExpStmt * isSgCExpStmt (SgStatement *pt);SgPointerAssignStmt * isSgPointerAssignStmt (SgStatement *pt); SgHeapStmt * isSgHeapStmt(SgStatement *pt); SgNullifyStmt * isSgNullifyStmt (SgStatement *pt); SgContinueStmt * isSgContinueStmt (SgStatement *pt); SgControlEndStmt * isSgControlEndStmt (SgStatement *pt);SgBreakStmt * isSgBreakStmt (SgStatement *pt); SgCycleStmt * isSgCycleStmt (SgStatement*pt); SgReturnStmt * isSgReturnStmt (SgStatement *pt); SgExitStmt * isSgExitStmt (SgStatement *pt); SgGotoStmt * isSgGotoStmt (SgStatement *pt); SgLabelListStmt * isSgLabelListStmt(SgStatement *pt); SgAssignedGotoStmt * isSgAssignedGotoStmt (SgStatement *pt); SgComputedGotoStmt * isSgComputedGotoStmt (SgStatement *pt); SgStopOrPauseStmt * isSgStopOrPauseStmt (SgStatement *pt); SgCallStmt* isSgCallStmt (SgStatement *pt); SgIOStmt * isSgIOStmt(SgStatement *pt); SgInputOutputStmt * isSgInputOutputStmt (SgStatement *pt); SgIOControlStmt * isSgIOControlStmt (SgStatement *pt); SgDeclarationStatement * isSgDeclarationStatement(SgStatement *pt); SgVarDeclStmt * isSgVarDeclStmt (SgStatement *pt); SgVarListDeclStmt *isSgVarListDeclStmt (SgStatement *pt); SgStructureDeclStmt * isSgStructureDeclStmt (SgStatement *pt); SgNestedVarListDeclStmt* isSgNestedVarListDeclStmt (SgStatement *pt); SgParame-Chapter 9: Example Programs9 Example Programs9.1 Restructure/*********************************************************************//*pC++/Sage++ Copyright (C) 1993*//* Indiana University University of Oregon University of Rennes*//*********************************************************************/#include <stdio.h>#include <malloc.h>#include "sage++user.h"//////////////this is an example of how to use the sage libraryto restructure fortran programs.

Характеристики

Список файлов учебной работы

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6529
Авторов
на СтудИзбе
301
Средний доход
с одного платного файла
Обучение Подробнее