source: CLRX/CLRadeonExtender/trunk/CLRX/amdasm/Assembler.h @ 4171

Last change on this file since 4171 was 4171, checked in by matszpk, 11 months ago

CLRadeonExtender: Asm: Add ISALinearDepHandler. Add '.rvlin' pseudo-op.

File size: 33.3 KB
Line 
1/*
2 *  CLRadeonExtender - Unofficial OpenCL Radeon Extensions Library
3 *  Copyright (C) 2014-2018 Mateusz Szpakowski
4 *
5 *  This library is free software; you can redistribute it and/or
6 *  modify it under the terms of the GNU Lesser General Public
7 *  License as published by the Free Software Foundation; either
8 *  version 2.1 of the License, or (at your option) any later version.
9 *
10 *  This library is distributed in the hope that it will be useful,
11 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 *  Lesser General Public License for more details.
14 *
15 *  You should have received a copy of the GNU Lesser General Public
16 *  License along with this library; if not, write to the Free Software
17 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18 */
19/*! \file Assembler.h
20 * \brief an assembler for Radeon GPU's
21 */
22
23#ifndef __CLRX_ASSEMBLER_H__
24#define __CLRX_ASSEMBLER_H__
25
26#include <CLRX/Config.h>
27#include <cstdint>
28#include <string>
29#include <istream>
30#include <ostream>
31#include <iostream>
32#include <vector>
33#include <utility>
34#include <stack>
35#include <list>
36#include <unordered_set>
37#include <unordered_map>
38#include <CLRX/utils/Utilities.h>
39#include <CLRX/utils/Containers.h>
40#include <CLRX/amdasm/Commons.h>
41#include <CLRX/amdasm/AsmSource.h>
42#include <CLRX/amdasm/AsmFormats.h>
43#include <CLRX/amdasm/AsmDefs.h>
44
45/// main namespace
46namespace CLRX
47{
48
49enum: cxuint {
50    ASM_POLICY_DEFAULT = CLRX_VERSION_NUMBER,        // version 107
51    ASM_POLICY_UNIFIED_SGPR_COUNT = CLRX_POLICY_UNIFIED_SGPR_COUNT
52};
53
54enum: Flags
55{
56    ASM_WARNINGS = 1,   ///< enable all warnings for assembler
57    ASM_FORCE_ADD_SYMBOLS = 2,  ///< force add symbols to binary
58    ASM_ALTMACRO = 4,   ///< enable altmacro mode
59    ASM_BUGGYFPLIT = 8, ///< buggy handling of fpliterals (including fp constants)
60    ASM_MACRONOCASE = 16, /// disable case-insensitive naming (default)
61    ASM_OLDMODPARAM = 32,   ///< use old modifier parametrization (values 0 and 1 only)
62    ASM_TESTRESOLVE = (1U<<30), ///< enable resolving symbols if ASM_TESTRUN enabled
63    ASM_TESTRUN = (1U<<31), ///< only for running tests
64    ASM_ALL = FLAGS_ALL&~(ASM_TESTRUN|ASM_TESTRESOLVE|ASM_BUGGYFPLIT|ASM_MACRONOCASE|
65                    ASM_OLDMODPARAM)  ///< all flags
66};
67
68struct AsmRegVar;
69
70/// ISA (register and regvar) Usage handler
71class ISAUsageHandler
72{
73public:
74    /// stgructure that hold read position to store later
75    struct ReadPos
76    {
77        size_t readOffset;  ///< read offset
78        size_t instrStructPos;  ///< position instrStructs
79        size_t regUsagesPos;    ///< position in reg usage
80        size_t regUsages2Pos;   ///< position in regUsage2
81        size_t regVarUsagesPos;    ///< position in regVarUsage
82        uint16_t pushedArgs;    ///< pushed argds number
83        cxbyte argPos;          ///< argument position
84        cxbyte argFlags;        ///< ???
85        bool isNext;            ///< isNext
86        bool useRegMode;        ///< true if in usereg mode
87    };
88protected:
89    std::vector<cxbyte> instrStruct;    ///< structure of register usage
90    std::vector<AsmRegUsageInt> regUsages;  ///< register usage
91    std::vector<AsmRegUsage2Int> regUsages2;  ///< register usage (by .usereg)
92    std::vector<AsmRegVarUsageInt> regVarUsages;    ///< regvar usage
93    const std::vector<cxbyte>& content; ///< code content
94    size_t lastOffset;  ///< last offset
95    size_t readOffset;  ///< read offset
96    size_t instrStructPos;  ///< position in instr struct
97    size_t regUsagesPos;    ///< position in reg usage
98    size_t regUsages2Pos;   ///< position in reg usage 2
99    size_t regVarUsagesPos; ///< position in regvar usage
100    uint16_t pushedArgs;    ///< pushed args
101    cxbyte argPos;      ///< argument position
102    cxbyte argFlags;    ///< ???
103    cxbyte defaultInstrSize;    ///< default instruction size
104    bool isNext;        ///< is next
105    bool useRegMode;    ///< true if in usereg mode
106   
107    void skipBytesInInstrStruct();
108    /// put space to offset
109    void putSpace(size_t offset);
110   
111    /// constructor
112    explicit ISAUsageHandler(const std::vector<cxbyte>& content);
113public:
114    /// destructor
115    virtual ~ISAUsageHandler();
116    /// copy this usage handler
117    virtual ISAUsageHandler* copy() const = 0;
118   
119    /// push regvar or register usage
120    void pushUsage(const AsmRegVarUsage& rvu);
121    /// rewind to start for reading
122    void rewind();
123    /// flush last pending register usages
124    void flush();
125    /// has next regvar usage
126    bool hasNext() const
127    { return isNext; }
128    /// get next usage
129    AsmRegVarUsage nextUsage();
130   
131    /// get reading position
132    ReadPos getReadPos() const
133    {
134        return { readOffset, instrStructPos, regUsagesPos, regUsages2Pos,
135            regVarUsagesPos, pushedArgs, argPos, argFlags, isNext, useRegMode };
136    }
137    /// set reading position
138    void setReadPos(const ReadPos rpos)
139    {
140        readOffset = rpos.readOffset;
141        instrStructPos = rpos.instrStructPos;
142        regUsagesPos = rpos.regUsagesPos;
143        regUsages2Pos = rpos.regUsages2Pos;
144        regVarUsagesPos = rpos.regVarUsagesPos;
145        pushedArgs = rpos.pushedArgs;
146        argPos = rpos.argPos;
147        argFlags = rpos.argFlags;
148        isNext = rpos.isNext;
149        useRegMode = rpos.useRegMode;
150    }
151   
152    /// push regvar or register from usereg pseudo-op
153    void pushUseRegUsage(const AsmRegVarUsage& rvu);
154   
155    /// get RW flags (used by assembler)
156    virtual cxbyte getRwFlags(AsmRegField regField, uint16_t rstart,
157                      uint16_t rend) const = 0;
158    /// get reg pair (used by assembler)
159    virtual std::pair<uint16_t,uint16_t> getRegPair(AsmRegField regField,
160                    cxbyte rwFlags) const = 0;
161    /// get usage dependencies around single instruction
162    virtual void getUsageDependencies(cxuint rvusNum, const AsmRegVarUsage* rvus,
163                    cxbyte* linearDeps) const = 0;
164};
165
166/// ISA regvar linear handler
167class ISALinearDepHandler
168{
169private:
170    std::vector<AsmRegVarLinearDep> regVarLinDeps;
171    size_t regVarLinDepsPos;
172public:
173    /// constructor
174    ISALinearDepHandler();
175   
176    /// get reading position
177    size_t getReadPos() const
178    { return regVarLinDepsPos; }
179    /// get reading position
180    void setReadPos(size_t pos)
181    { regVarLinDepsPos = pos; }
182    /// push linear dependency
183    void pushLinearDep(const AsmRegVarLinearDep& linearDep);
184    /// rewind read position to start
185    void rewind();
186    /// return true if has next
187    bool hasNext() const
188    { return regVarLinDepsPos < regVarLinDeps.size(); }
189    /// get next linear dependency
190    AsmRegVarLinearDep nextLinearDep();
191};
192
193/// GCN (register and regvar) Usage handler
194class GCNUsageHandler: public ISAUsageHandler
195{
196private:
197    uint16_t archMask;
198public:
199    /// constructor
200    GCNUsageHandler(const std::vector<cxbyte>& content, uint16_t archMask);
201    /// destructor
202    ~GCNUsageHandler();
203   
204    /// copy this usage handler
205    ISAUsageHandler* copy() const;
206   
207    cxbyte getRwFlags(AsmRegField regFied, uint16_t rstart, uint16_t rend) const;
208    std::pair<uint16_t,uint16_t> getRegPair(AsmRegField regField, cxbyte rwFlags) const;
209    void getUsageDependencies(cxuint rvusNum, const AsmRegVarUsage* rvus,
210                    cxbyte* linearDeps) const;
211};
212
213/// ISA assembler class
214class ISAAssembler: public NonCopyableAndNonMovable
215{
216protected:
217    Assembler& assembler;       ///< assembler
218   
219    /// print warning for position pointed by line pointer
220    void printWarning(const char* linePtr, const char* message);
221    /// print error for position pointed by line pointer
222    void printError(const char* linePtr, const char* message);
223    /// print warning for source position
224    void printWarning(const AsmSourcePos& sourcePos, const char* message);
225    /// print error for source position
226    void printError(const AsmSourcePos& sourcePos, const char* message);
227    /// print warning about integer out of range
228    void printWarningForRange(cxuint bits, uint64_t value, const AsmSourcePos& pos,
229                cxbyte signess = WS_BOTH);
230    void addCodeFlowEntry(cxuint sectionId, const AsmCodeFlowEntry& entry);
231    /// constructor
232    explicit ISAAssembler(Assembler& assembler);
233public:
234    /// destructor
235    virtual ~ISAAssembler();
236    /// create usage handler
237    virtual ISAUsageHandler* createUsageHandler(std::vector<cxbyte>& content) const = 0;
238   
239    /// assemble single line
240    virtual void assemble(const CString& mnemonic, const char* mnemPlace,
241              const char* linePtr, const char* lineEnd, std::vector<cxbyte>& output,
242              ISAUsageHandler* usageHandler) = 0;
243    /// resolve code with location, target and value
244    virtual bool resolveCode(const AsmSourcePos& sourcePos, cxuint targetSectionId,
245                 cxbyte* sectionData, size_t offset, AsmExprTargetType targetType,
246                 cxuint sectionId, uint64_t value) = 0;
247    /// check if name is mnemonic
248    virtual bool checkMnemonic(const CString& mnemonic) const = 0;
249    /// set allocated registers (if regs is null then reset them)
250    virtual void setAllocatedRegisters(const cxuint* regs = nullptr,
251                Flags regFlags = 0) = 0;
252    /// get allocated register numbers after assemblying
253    virtual const cxuint* getAllocatedRegisters(size_t& regTypesNum,
254                Flags& regFlags) const = 0;
255    /// get max registers number
256    virtual void getMaxRegistersNum(size_t& regTypesNum, cxuint* maxRegs) const = 0;
257    /// get registers ranges
258    virtual void getRegisterRanges(size_t& regTypesNum, cxuint* regRanges) const = 0;
259    /// fill alignment when value is not given
260    virtual void fillAlignment(size_t size, cxbyte* output) = 0;
261    /// parse register range
262    virtual bool parseRegisterRange(const char*& linePtr, cxuint& regStart,
263                        cxuint& regEnd, const AsmRegVar*& regVar) = 0;
264    /// return true if expresion of target fit to value with specified bits
265    virtual bool relocationIsFit(cxuint bits, AsmExprTargetType tgtType) = 0;
266    /// parse register type for '.reg' pseudo-op
267    virtual bool parseRegisterType(const char*& linePtr,
268                       const char* end, cxuint& type) = 0;
269    /// get size of instruction
270    virtual size_t getInstructionSize(size_t codeSize, const cxbyte* code) const = 0;
271};
272
273/// GCN arch assembler
274class GCNAssembler: public ISAAssembler
275{
276public:
277    /// register pool numbers
278    struct Regs {
279        cxuint sgprsNum;    ///< SGPRs number
280        cxuint vgprsNum;    ///< VGPRs number
281        Flags regFlags; ///< define what extra register must be included
282    };
283private:
284    friend struct GCNAsmUtils; // INTERNAL LOGIC
285    union {
286        Regs regs;
287        cxuint regTable[2];
288    };
289    uint16_t curArchMask;
290    cxbyte currentRVUIndex;
291    AsmRegVarUsage instrRVUs[6];
292   
293    void resetInstrRVUs()
294    {
295        for (AsmRegVarUsage& rvu: instrRVUs)
296            rvu.regField = ASMFIELD_NONE;
297    }
298    void setCurrentRVU(cxbyte idx)
299    { currentRVUIndex = idx; }
300   
301    void setRegVarUsage(const AsmRegVarUsage& rvu)
302    { instrRVUs[currentRVUIndex] = rvu; }
303   
304    void flushInstrRVUs(ISAUsageHandler* usageHandler)
305    {
306        for (const AsmRegVarUsage& rvu: instrRVUs)
307            if (rvu.regField != ASMFIELD_NONE)
308                usageHandler->pushUsage(rvu);
309    }
310public:
311    /// constructor
312    explicit GCNAssembler(Assembler& assembler);
313    /// destructor
314    ~GCNAssembler();
315   
316    ISAUsageHandler* createUsageHandler(std::vector<cxbyte>& content) const;
317   
318    void assemble(const CString& mnemonic, const char* mnemPlace, const char* linePtr,
319                  const char* lineEnd, std::vector<cxbyte>& output,
320                  ISAUsageHandler* usageHandler);
321    bool resolveCode(const AsmSourcePos& sourcePos, cxuint targetSectionId,
322                 cxbyte* sectionData, size_t offset, AsmExprTargetType targetType,
323                 cxuint sectionId, uint64_t value);
324    bool checkMnemonic(const CString& mnemonic) const;
325    void setAllocatedRegisters(const cxuint* regs, Flags regFlags);
326    const cxuint* getAllocatedRegisters(size_t& regTypesNum, Flags& regFlags) const;
327    void getMaxRegistersNum(size_t& regTypesNum, cxuint* maxRegs) const;
328    void getRegisterRanges(size_t& regTypesNum, cxuint* regRanges) const;
329    void fillAlignment(size_t size, cxbyte* output);
330    bool parseRegisterRange(const char*& linePtr, cxuint& regStart, cxuint& regEnd,
331                const AsmRegVar*& regVar);
332    bool relocationIsFit(cxuint bits, AsmExprTargetType tgtType);
333    bool parseRegisterType(const char*& linePtr, const char* end, cxuint& type);
334    size_t getInstructionSize(size_t codeSize, const cxbyte* code) const;
335};
336
337class AsmRegAllocator
338{
339public:
340    struct NextBlock
341    {
342        size_t block;
343        bool isCall;
344    };
345    struct SSAInfo
346    {
347        size_t ssaIdBefore; ///< SSA id before first SSA in block
348        size_t ssaIdFirst; // SSA id at first change
349        size_t ssaId;   ///< original SSA id
350        size_t ssaIdLast; ///< last SSA id in last
351        size_t ssaIdChange; ///< number of SSA id changes
352        size_t firstPos;    ///< first position in code block (section offset)
353        size_t lastPos;     ///< last position in code block (section offset)
354        bool readBeforeWrite;   ///< have read before write
355        SSAInfo(size_t _bssaId = SIZE_MAX, size_t _ssaIdF = SIZE_MAX,
356                size_t _ssaId = SIZE_MAX, size_t _ssaIdL = SIZE_MAX,
357                size_t _ssaIdChange = 0, bool _readBeforeWrite = false)
358            : ssaIdBefore(_bssaId), ssaIdFirst(_ssaIdF), ssaId(_ssaId),
359              ssaIdLast(_ssaIdL), ssaIdChange(_ssaIdChange),
360              readBeforeWrite(_readBeforeWrite)
361        { }
362    };
363    struct CodeBlock
364    {
365        size_t start, end; // place in code
366        // next blocks rules:
367        // if only one and next block have index: empty.
368        // if have calls, then implicitly the last next block have next block index
369        //     and it is not inserted into nexts list.
370        // otherwise nexts list contains next blocks
371        std::vector<NextBlock> nexts; ///< nexts blocks, if empty then direct next block
372        bool haveCalls; ///< code have calls at its end
373        bool haveReturn; ///< code have return from routine
374        bool haveEnd;   ///< code have end
375        // key - regvar, value - SSA info for this regvar
376        std::unordered_map<AsmSingleVReg, SSAInfo> ssaInfoMap;
377        ISAUsageHandler::ReadPos usagePos;
378    };
379   
380    typedef Array<std::pair<size_t, size_t> > OutLiveness;
381   
382     // first - orig ssaid, second - dest ssaid
383    typedef std::pair<size_t, size_t> SSAReplace;
384    typedef std::unordered_map<AsmSingleVReg, VectorSet<SSAReplace> > SSAReplacesMap;
385    // interference graph type
386    typedef Array<std::unordered_set<size_t> > InterGraph;
387    typedef std::unordered_map<AsmSingleVReg, std::vector<size_t> > VarIndexMap;
388    struct LinearDep
389    {
390        cxbyte align;
391        VectorSet<size_t> prevVidxes;
392        VectorSet<size_t> nextVidxes;
393    };
394   
395    struct VIdxSetEntry
396    {
397        std::unordered_set<size_t> vs[MAX_REGTYPES_NUM];
398    };
399private:
400    Assembler& assembler;
401    std::vector<CodeBlock> codeBlocks;
402    SSAReplacesMap ssaReplacesMap;
403    size_t regTypesNum;
404   
405    Array<OutLiveness> outLivenesses[MAX_REGTYPES_NUM];
406    size_t graphVregsCounts[MAX_REGTYPES_NUM];
407    VarIndexMap vregIndexMaps[MAX_REGTYPES_NUM]; // indices to igraph for 2 reg types
408    InterGraph interGraphs[MAX_REGTYPES_NUM]; // for 2 register
409    Array<cxuint> graphColorMaps[MAX_REGTYPES_NUM];
410    std::unordered_map<size_t, LinearDep> linearDepMaps[MAX_REGTYPES_NUM];
411    // key - routine block, value - set of svvregs (lv indexes) used in routine
412    std::unordered_map<size_t, VIdxSetEntry> vidxRoutineMap;
413    // key - call block, value - set of svvregs (lv indexes) used between this call point
414    std::unordered_map<size_t, VIdxSetEntry> vidxCallMap;
415   
416public:
417    AsmRegAllocator(Assembler& assembler);
418    // constructor for testing
419    AsmRegAllocator(Assembler& assembler, const std::vector<CodeBlock>& codeBlocks,
420                const SSAReplacesMap& ssaReplacesMap);
421   
422    void createCodeStructure(const std::vector<AsmCodeFlowEntry>& codeFlow,
423             size_t codeSize, const cxbyte* code);
424    void createSSAData(ISAUsageHandler& usageHandler);
425    void applySSAReplaces();
426    void createLivenesses(ISAUsageHandler& usageHandler);
427    void createInterferenceGraph();
428    void colorInterferenceGraph();
429   
430    void allocateRegisters(cxuint sectionId);
431   
432    const std::vector<CodeBlock>& getCodeBlocks() const
433    { return codeBlocks; }
434    const SSAReplacesMap& getSSAReplacesMap() const
435    { return ssaReplacesMap; }
436    const Array<OutLiveness>* getOutLivenesses() const
437    { return outLivenesses; }
438   
439    const std::unordered_map<size_t, LinearDep>* getLinearDepMaps() const
440    { return linearDepMaps; }
441   
442    const VarIndexMap* getVregIndexMaps() const
443    { return vregIndexMaps; }
444   
445    const std::unordered_map<size_t, VIdxSetEntry>& getVIdxRoutineMap() const
446    { return vidxRoutineMap; }
447    const std::unordered_map<size_t, VIdxSetEntry>& getVIdxCallMap() const
448    { return vidxCallMap; }
449};
450
451/// type of clause
452enum class AsmClauseType
453{
454    IF,     ///< if clause
455    ELSEIF, ///< elseif clause
456    ELSE,   ///< else clause
457    REPEAT, ///< rept clause or irp/irpc clause
458    MACRO   ///< macro clause
459};
460
461/// assembler's clause (if,else,macro,rept)
462struct AsmClause
463{
464    AsmClauseType type; ///< type of clause
465    AsmSourcePos sourcePos;   ///< position in source code
466    bool condSatisfied; ///< if conditional clause has already been satisfied
467    AsmSourcePos prevIfPos; ///< position of previous if-clause
468};
469
470/// main class of assembler
471class Assembler: public NonCopyableAndNonMovable
472{
473public:
474    /// defined symbol entry
475    typedef std::pair<CString, uint64_t> DefSym;
476    /// kernel map type
477    typedef std::unordered_map<CString, cxuint> KernelMap;
478private:
479    friend class AsmStreamInputFilter;
480    friend class AsmMacroInputFilter;
481    friend class AsmForInputFilter;
482    friend class AsmExpression;
483    friend class AsmFormatHandler;
484    friend class AsmRawCodeHandler;
485    friend class AsmAmdHandler;
486    friend class AsmAmdCL2Handler;
487    friend class AsmGalliumHandler;
488    friend class AsmROCmHandler;
489    friend class ISAAssembler;
490    friend class AsmRegAllocator;
491   
492    friend struct AsmParseUtils; // INTERNAL LOGIC
493    friend struct AsmPseudoOps; // INTERNAL LOGIC
494    friend struct AsmGalliumPseudoOps; // INTERNAL LOGIC
495    friend struct AsmAmdPseudoOps; // INTERNAL LOGIC
496    friend struct AsmAmdCL2PseudoOps; // INTERNAL LOGIC
497    friend struct AsmROCmPseudoOps; // INTERNAL LOGIC
498    friend struct GCNAsmUtils; // INTERNAL LOGIC
499
500    Array<CString> filenames;
501    BinaryFormat format;
502    GPUDeviceType deviceType;
503    uint32_t driverVersion;
504    uint32_t llvmVersion; // GalliumCompute
505    bool _64bit;    ///
506    bool newROCmBinFormat;
507    bool good;
508    bool resolvingRelocs;
509    bool doNotRemoveFromSymbolClones;
510    cxuint policyVersion;
511    ISAAssembler* isaAssembler;
512    std::vector<DefSym> defSyms;
513    std::vector<CString> includeDirs;
514    std::vector<AsmSection> sections;
515    std::vector<Array<cxuint> > relSpacesSections;
516    std::unordered_set<AsmSymbolEntry*> symbolSnapshots;
517    std::unordered_set<AsmSymbolEntry*> symbolClones;
518    std::vector<AsmExpression*> unevalExpressions;
519    std::vector<AsmRelocation> relocations;
520    AsmScope globalScope;
521    AsmMacroMap macroMap;
522    std::stack<AsmScope*> scopeStack;
523    std::vector<AsmScope*> abandonedScopes;
524    AsmScope* currentScope;
525    KernelMap kernelMap;
526    std::vector<AsmKernel> kernels;
527    /// register variables
528    Flags flags;
529    uint64_t macroCount;
530    uint64_t localCount; // macro's local count
531    bool alternateMacro;
532    bool buggyFPLit;
533    bool macroCase;
534    bool oldModParam;
535   
536    cxuint inclusionLevel;
537    cxuint macroSubstLevel;
538    cxuint repetitionLevel;
539    bool lineAlreadyRead; // if line already read
540   
541    size_t lineSize;
542    const char* line;
543    bool endOfAssembly;
544    bool sectionDiffsPrepared;
545   
546    cxuint filenameIndex;
547    std::stack<AsmInputFilter*> asmInputFilters;
548    AsmInputFilter* currentInputFilter;
549   
550    std::ostream& messageStream;
551    std::ostream& printStream;
552   
553    AsmFormatHandler* formatHandler;
554   
555    std::stack<AsmClause> clauses;
556   
557    cxuint currentKernel;
558    cxuint& currentSection;
559    uint64_t& currentOutPos;
560   
561    bool withSectionDiffs() const
562    { return formatHandler!=nullptr && formatHandler->isSectionDiffsResolvable(); }
563   
564    AsmSourcePos getSourcePos(LineCol lineCol) const
565    {
566        return { currentInputFilter->getMacroSubst(), currentInputFilter->getSource(),
567            lineCol.lineNo, lineCol.colNo };
568    }
569   
570    AsmSourcePos getSourcePos(size_t pos) const
571    { return currentInputFilter->getSourcePos(pos); }
572    AsmSourcePos getSourcePos(const char* linePtr) const
573    { return getSourcePos(linePtr-line); }
574   
575    void printWarning(const AsmSourcePos& pos, const char* message);
576    void printError(const AsmSourcePos& pos, const char* message);
577   
578    void printWarning(const char* linePtr, const char* message)
579    { printWarning(getSourcePos(linePtr), message); }
580    void printError(const char* linePtr, const char* message)
581    { printError(getSourcePos(linePtr), message); }
582   
583    void printWarning(LineCol lineCol, const char* message)
584    { printWarning(getSourcePos(lineCol), message); }
585    void printError(LineCol lineCol, const char* message)
586    { printError(getSourcePos(lineCol), message); }
587   
588    LineCol translatePos(const char* linePtr) const
589    { return currentInputFilter->translatePos(linePtr-line); }
590    LineCol translatePos(size_t pos) const
591    { return currentInputFilter->translatePos(pos); }
592   
593    bool parseLiteral(uint64_t& value, const char*& linePtr);
594    bool parseLiteralNoError(uint64_t& value, const char*& linePtr);
595    bool parseString(std::string& outString, const char*& linePtr);
596   
597    enum class ParseState
598    {
599        FAILED = 0,
600        PARSED,
601        MISSING // missing element
602    };
603   
604    /** parse symbol
605     * \return state
606     */
607    ParseState parseSymbol(const char*& linePtr, AsmSymbolEntry*& entry,
608                   bool localLabel = true, bool dontCreateSymbol = false);
609    bool skipSymbol(const char*& linePtr);
610   
611    bool setSymbol(AsmSymbolEntry& symEntry, uint64_t value, cxuint sectionId);
612   
613    bool assignSymbol(const CString& symbolName, const char* symbolPlace,
614                  const char* linePtr, bool reassign = true, bool baseExpr = false);
615   
616    bool assignOutputCounter(const char* symbolPlace, uint64_t value, cxuint sectionId,
617                     cxbyte fillValue = 0);
618   
619    void parsePseudoOps(const CString& firstName, const char* stmtPlace,
620                const char* linePtr);
621   
622    /// exitm - exit macro mode
623    bool skipClauses(bool exitm = false);
624    bool putMacroContent(RefPtr<AsmMacro> macro);
625    bool putRepetitionContent(AsmRepeat& repeat);
626   
627    void initializeOutputFormat();
628   
629    bool pushClause(const char* string, AsmClauseType clauseType)
630    {
631        bool included; // to ignore
632        return pushClause(string, clauseType, true, included);
633    }
634    bool pushClause(const char* string, AsmClauseType clauseType,
635                  bool satisfied, bool& included);
636     // return false when failed (for example no clauses)
637    bool popClause(const char* string, AsmClauseType clauseType);
638   
639    // recursive function to find scope in scope
640    AsmScope* findScopeInScope(AsmScope* scope, const CString& scopeName,
641                    std::unordered_set<AsmScope*>& scopeSet);
642    // find scope by identifier
643    AsmScope* getRecurScope(const CString& scopePlace, bool ignoreLast = false,
644                    const char** lastStep = nullptr);
645    // find symbol in scopes
646    // internal recursive function to find symbol in scope
647    AsmSymbolEntry* findSymbolInScopeInt(AsmScope* scope, const CString& symName,
648                    std::unordered_set<AsmScope*>& scopeSet);
649    // scope - return scope from scoped name
650    AsmSymbolEntry* findSymbolInScope(const CString& symName, AsmScope*& scope,
651                      CString& sameSymName, bool insertMode = false);
652    // similar to map::insert, but returns pointer
653    std::pair<AsmSymbolEntry*, bool> insertSymbolInScope(const CString& symName,
654                 const AsmSymbol& symbol);
655   
656    // internal recursive function to find symbol in scope
657    AsmRegVarEntry* findRegVarInScopeInt(AsmScope* scope, const CString& rvName,
658                    std::unordered_set<AsmScope*>& scopeSet);
659    // scope - return scope from scoped name
660    AsmRegVarEntry* findRegVarInScope(const CString& rvName, AsmScope*& scope,
661                      CString& sameRvName, bool insertMode = false);
662    // similar to map::insert, but returns pointer
663    std::pair<AsmRegVarEntry*, bool> insertRegVarInScope(const CString& rvName,
664                 const AsmRegVar& regVar);
665   
666    // create scope
667    bool getScope(AsmScope* parent, const CString& scopeName, AsmScope*& scope);
668    // push new scope level
669    bool pushScope(const CString& scopeName);
670    bool popScope();
671   
672    /// returns false when includeLevel is too deep, throw error if failed a file opening
673    bool includeFile(const char* pseudoOpPlace, const std::string& filename);
674   
675    ParseState makeMacroSubstitution(const char* string);
676   
677    bool parseMacroArgValue(const char*& linePtr, std::string& outStr);
678   
679    void putData(size_t size, const cxbyte* data)
680    {
681        AsmSection& section = sections[currentSection];
682        section.content.insert(section.content.end(), data, data+size);
683        currentOutPos += size;
684    }
685   
686    cxbyte* reserveData(size_t size, cxbyte fillValue = 0);
687   
688    void goToMain(const char* pseudoOpPlace);
689    void goToKernel(const char* pseudoOpPlace, const char* kernelName);
690    void goToSection(const char* pseudoOpPlace, const char* sectionName, uint64_t align=0);
691    void goToSection(const char* pseudoOpPlace, const char* sectionName,
692                     AsmSectionType type, Flags flags, uint64_t align=0);
693    void goToSection(const char* pseudoOpPlace, cxuint sectionId, uint64_t align=0);
694   
695    void printWarningForRange(cxuint bits, uint64_t value, const AsmSourcePos& pos,
696                  cxbyte signess = WS_BOTH);
697   
698    bool isAddressableSection() const
699    {
700        return currentSection==ASMSECT_ABS ||
701                    (sections[currentSection].flags & ASMSECT_ADDRESSABLE) != 0;
702    }
703    bool isWriteableSection() const
704    {
705        return currentSection!=ASMSECT_ABS &&
706                (sections[currentSection].flags & ASMSECT_WRITEABLE) != 0;
707    }
708    bool isResolvableSection() const
709    {
710        return currentSection==ASMSECT_ABS ||
711                (sections[currentSection].flags & ASMSECT_UNRESOLVABLE) == 0;
712    }
713    bool isResolvableSection(cxuint sectionId) const
714    {
715        return sectionId==ASMSECT_ABS ||
716                (sections[sectionId].flags & ASMSECT_UNRESOLVABLE) == 0;
717    }
718   
719    // oldKernels and newKernels must be sorted
720    void handleRegionsOnKernels(const std::vector<cxuint>& newKernels,
721                const std::vector<cxuint>& oldKernels, cxuint codeSection);
722   
723    void tryToResolveSymbol(AsmSymbolEntry& symEntry);
724    void tryToResolveSymbols(AsmScope* scope);
725    void printUnresolvedSymbols(AsmScope* scope);
726   
727    bool resolveExprTarget(const AsmExpression* expr, uint64_t value, cxuint sectionId);
728   
729    void cloneSymEntryIfNeeded(AsmSymbolEntry& symEntry);
730   
731    void undefineSymbol(AsmSymbolEntry& symEntry);
732   
733protected:
734    /// helper for testing
735    bool readLine();
736public:
737    /// constructor with filename and input stream
738    /**
739     * \param filename filename
740     * \param input input stream
741     * \param flags assembler flags
742     * \param format output format type
743     * \param deviceType GPU device type
744     * \param msgStream stream for warnings and errors
745     * \param printStream stream for printing message by .print pseudo-ops
746     */
747    explicit Assembler(const CString& filename, std::istream& input, Flags flags = 0,
748              BinaryFormat format = BinaryFormat::AMD,
749              GPUDeviceType deviceType = GPUDeviceType::CAPE_VERDE,
750              std::ostream& msgStream = std::cerr, std::ostream& printStream = std::cout);
751   
752    /// constructor with filename and input stream
753    /**
754     * \param filenames filenames
755     * \param flags assembler flags
756     * \param format output format type
757     * \param deviceType GPU device type
758     * \param msgStream stream for warnings and errors
759     * \param printStream stream for printing message by .print pseudo-ops
760     */
761    explicit Assembler(const Array<CString>& filenames, Flags flags = 0,
762              BinaryFormat format = BinaryFormat::AMD,
763              GPUDeviceType deviceType = GPUDeviceType::CAPE_VERDE,
764              std::ostream& msgStream = std::cerr, std::ostream& printStream = std::cout);
765    /// destructor
766    ~Assembler();
767   
768    /// main routine to assemble code
769    bool assemble();
770   
771    /// write binary to file
772    void writeBinary(const char* filename) const;
773    /// write binary to stream
774    void writeBinary(std::ostream& outStream) const;
775    /// write binary to array
776    void writeBinary(Array<cxbyte>& array) const;
777   
778    /// get AMD driver version
779    uint32_t getDriverVersion() const
780    { return driverVersion; }
781    /// set AMD driver version
782    void setDriverVersion(uint32_t driverVersion)
783    { this->driverVersion = driverVersion; }
784   
785    /// get LLVM version
786    uint32_t getLLVMVersion() const
787    { return llvmVersion; }
788    /// set LLVM version
789    void setLLVMVersion(uint32_t llvmVersion)
790    { this->llvmVersion = llvmVersion; }
791   
792    /// get GPU device type
793    GPUDeviceType getDeviceType() const
794    { return deviceType; }
795    /// set GPU device type
796    void setDeviceType(const GPUDeviceType deviceType)
797    { this->deviceType = deviceType; }
798    /// get binary format
799    BinaryFormat getBinaryFormat() const
800    { return format; }
801    /// set binary format
802    void setBinaryFormat(BinaryFormat binFormat)
803    { format = binFormat; }
804    /// get bitness (true if 64-bit)
805    bool is64Bit() const
806    { return _64bit; }
807    /// set bitness (true if 64-bit)
808    void set64Bit(bool this64Bit)
809    {  _64bit = this64Bit; }
810    /// is new ROCm binary format
811    bool isNewROCmBinFormat() const
812    { return newROCmBinFormat; }
813    /// set new ROCm binary format
814    void setNewROCmBinFormat(bool newFmt)
815    { newROCmBinFormat = newFmt; }
816    /// get policy version
817    cxuint getPolicyVersion() const
818    { return policyVersion; }
819    /// set policy version
820    void setPolicyVersion(cxuint pv)
821    { policyVersion = pv; }
822    /// get flags
823    Flags getFlags() const
824    { return flags; }
825    /// set flags
826    void setFlags(Flags flags)
827    { this->flags = flags; }
828    /// get true if altMacro enabled
829    bool isAltMacro() const
830    { return alternateMacro; }
831    /// get true if macroCase enabled
832    bool isMacroCase() const
833    { return macroCase; }
834    /// get true if oldModParam enabled (old modifier parametrization)
835    bool isOldModParam() const
836    { return oldModParam; }
837    /// get true if buggyFPLit enabled
838    bool isBuggyFPLit() const
839    { return buggyFPLit; }
840    /// get include directory list
841    const std::vector<CString>& getIncludeDirs() const
842    { return includeDirs; }
843    /// adds include directory
844    void addIncludeDir(const CString& includeDir);
845    /// get symbols map
846    const AsmSymbolMap& getSymbolMap() const
847    { return globalScope.symbolMap; }
848    /// get sections
849    const std::vector<AsmSection>& getSections() const
850    { return sections; }
851    // get first sections for rel spaces
852    const std::vector<Array<cxuint> >& getRelSpacesSections() const
853    { return relSpacesSections; }
854    /// get kernel map
855    const KernelMap& getKernelMap() const
856    { return kernelMap; }
857    /// get kernels
858    const std::vector<AsmKernel>& getKernels() const
859    { return kernels; }
860    /// get regvar map
861    const AsmRegVarMap& getRegVarMap() const
862    { return globalScope.regVarMap; }
863    /// add regvar
864    bool addRegVar(const CString& name, const AsmRegVar& var)
865    { return insertRegVarInScope(name, var).second; }
866    /// get regvar by name
867    bool getRegVar(const CString& name, const AsmRegVar*& regVar);
868   
869    /// get global scope
870    const AsmScope& getGlobalScope() const
871    { return globalScope; }
872   
873    /// returns true if symbol contains absolute value
874    bool isAbsoluteSymbol(const AsmSymbol& symbol) const;
875   
876    /// add initiali defsyms
877    void addInitialDefSym(const CString& symName, uint64_t value);
878   
879    /// get format handler
880    const AsmFormatHandler* getFormatHandler() const
881    { return formatHandler; }
882};
883
884inline void ISAAssembler::printWarning(const char* linePtr, const char* message)
885{ assembler.printWarning(linePtr, message); }
886
887inline void ISAAssembler::printError(const char* linePtr, const char* message)
888{ assembler.printError(linePtr, message); }
889
890inline void ISAAssembler::printWarningForRange(cxuint bits, uint64_t value,
891                   const AsmSourcePos& pos, cxbyte signess)
892{ assembler.printWarningForRange(bits, value, pos, signess); }
893
894inline void ISAAssembler::printWarning(const AsmSourcePos& sourcePos, const char* message)
895{ assembler.printWarning(sourcePos, message); }
896
897inline void ISAAssembler::printError(const AsmSourcePos& sourcePos, const char* message)
898{ assembler.printError(sourcePos, message); }
899
900inline void ISAAssembler::addCodeFlowEntry(cxuint sectionId, const AsmCodeFlowEntry& entry)
901{ assembler.sections[sectionId].addCodeFlowEntry(entry); }
902
903};
904
905#endif
Note: See TracBrowser for help on using the repository browser.