1 //===- COFFAsmParser.cpp - COFF Assembly Parser ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
11 #include "llvm/ADT/StringSwitch.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCParser/MCAsmLexer.h"
17 #include "llvm/MC/MCRegisterInfo.h"
18 #include "llvm/MC/MCSectionCOFF.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCTargetAsmParser.h"
21 #include "llvm/Support/COFF.h"
26 class COFFAsmParser : public MCAsmParserExtension {
27 template<bool (COFFAsmParser::*HandlerMethod)(StringRef, SMLoc)>
28 void addDirectiveHandler(StringRef Directive) {
29 MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
30 this, HandleDirective<COFFAsmParser, HandlerMethod>);
31 getParser().addDirectiveHandler(Directive, Handler);
34 bool ParseSectionSwitch(StringRef Section,
35 unsigned Characteristics,
38 bool ParseSectionName(StringRef &SectionName);
39 bool ParseSectionFlags(StringRef FlagsString, unsigned* Flags);
41 virtual void Initialize(MCAsmParser &Parser) {
42 // Call the base implementation.
43 MCAsmParserExtension::Initialize(Parser);
45 addDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveText>(".text");
46 addDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveData>(".data");
47 addDirectiveHandler<&COFFAsmParser::ParseSectionDirectiveBSS>(".bss");
48 addDirectiveHandler<&COFFAsmParser::ParseDirectiveSection>(".section");
49 addDirectiveHandler<&COFFAsmParser::ParseDirectiveDef>(".def");
50 addDirectiveHandler<&COFFAsmParser::ParseDirectiveScl>(".scl");
51 addDirectiveHandler<&COFFAsmParser::ParseDirectiveType>(".type");
52 addDirectiveHandler<&COFFAsmParser::ParseDirectiveEndef>(".endef");
53 addDirectiveHandler<&COFFAsmParser::ParseDirectiveSecRel32>(".secrel32");
54 addDirectiveHandler<&COFFAsmParser::ParseDirectiveLinkOnce>(".linkonce");
56 // Win64 EH directives.
57 addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveStartProc>(
59 addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndProc>(
61 addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveStartChained>(
63 addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndChained>(
65 addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveHandler>(
67 addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveHandlerData>(
69 addDirectiveHandler<&COFFAsmParser::ParseSEHDirectivePushReg>(
71 addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSetFrame>(
73 addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveAllocStack>(
75 addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSaveReg>(
77 addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveSaveXMM>(
79 addDirectiveHandler<&COFFAsmParser::ParseSEHDirectivePushFrame>(
81 addDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveEndProlog>(
83 addDirectiveHandler<&COFFAsmParser::ParseDirectiveSymbolAttribute>(".weak");
86 bool ParseSectionDirectiveText(StringRef, SMLoc) {
87 return ParseSectionSwitch(".text",
88 COFF::IMAGE_SCN_CNT_CODE
89 | COFF::IMAGE_SCN_MEM_EXECUTE
90 | COFF::IMAGE_SCN_MEM_READ,
91 SectionKind::getText());
93 bool ParseSectionDirectiveData(StringRef, SMLoc) {
94 return ParseSectionSwitch(".data",
95 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
96 | COFF::IMAGE_SCN_MEM_READ
97 | COFF::IMAGE_SCN_MEM_WRITE,
98 SectionKind::getDataRel());
100 bool ParseSectionDirectiveBSS(StringRef, SMLoc) {
101 return ParseSectionSwitch(".bss",
102 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA
103 | COFF::IMAGE_SCN_MEM_READ
104 | COFF::IMAGE_SCN_MEM_WRITE,
105 SectionKind::getBSS());
108 bool ParseDirectiveSection(StringRef, SMLoc);
109 bool ParseDirectiveDef(StringRef, SMLoc);
110 bool ParseDirectiveScl(StringRef, SMLoc);
111 bool ParseDirectiveType(StringRef, SMLoc);
112 bool ParseDirectiveEndef(StringRef, SMLoc);
113 bool ParseDirectiveSecRel32(StringRef, SMLoc);
114 bool ParseDirectiveLinkOnce(StringRef, SMLoc);
116 // Win64 EH directives.
117 bool ParseSEHDirectiveStartProc(StringRef, SMLoc);
118 bool ParseSEHDirectiveEndProc(StringRef, SMLoc);
119 bool ParseSEHDirectiveStartChained(StringRef, SMLoc);
120 bool ParseSEHDirectiveEndChained(StringRef, SMLoc);
121 bool ParseSEHDirectiveHandler(StringRef, SMLoc);
122 bool ParseSEHDirectiveHandlerData(StringRef, SMLoc);
123 bool ParseSEHDirectivePushReg(StringRef, SMLoc);
124 bool ParseSEHDirectiveSetFrame(StringRef, SMLoc);
125 bool ParseSEHDirectiveAllocStack(StringRef, SMLoc);
126 bool ParseSEHDirectiveSaveReg(StringRef, SMLoc);
127 bool ParseSEHDirectiveSaveXMM(StringRef, SMLoc);
128 bool ParseSEHDirectivePushFrame(StringRef, SMLoc);
129 bool ParseSEHDirectiveEndProlog(StringRef, SMLoc);
131 bool ParseAtUnwindOrAtExcept(bool &unwind, bool &except);
132 bool ParseSEHRegisterNumber(unsigned &RegNo);
133 bool ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc);
138 } // end annonomous namespace.
140 static SectionKind computeSectionKind(unsigned Flags) {
141 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
142 return SectionKind::getText();
143 if (Flags & COFF::IMAGE_SCN_MEM_READ &&
144 (Flags & COFF::IMAGE_SCN_MEM_WRITE) == 0)
145 return SectionKind::getReadOnly();
146 return SectionKind::getDataRel();
149 bool COFFAsmParser::ParseSectionFlags(StringRef FlagsString, unsigned* Flags) {
162 bool ReadOnlyRemoved = false;
163 unsigned SecFlags = None;
165 for (unsigned i = 0; i < FlagsString.size(); ++i) {
166 switch (FlagsString[i]) {
171 case 'b': // bss section
173 if (SecFlags & InitData)
174 return TokError("conflicting section flags 'b' and 'd'.");
178 case 'd': // data section
179 SecFlags |= InitData;
180 if (SecFlags & Alloc)
181 return TokError("conflicting section flags 'b' and 'd'.");
182 SecFlags &= ~NoWrite;
183 if ((SecFlags & NoLoad) == 0)
187 case 'n': // section is not loaded
192 case 'r': // read-only
193 ReadOnlyRemoved = false;
195 if ((SecFlags & Code) == 0)
196 SecFlags |= InitData;
197 if ((SecFlags & NoLoad) == 0)
201 case 's': // shared section
202 SecFlags |= Shared | InitData;
203 SecFlags &= ~NoWrite;
204 if ((SecFlags & NoLoad) == 0)
208 case 'w': // writable
209 SecFlags &= ~NoWrite;
210 ReadOnlyRemoved = true;
213 case 'x': // executable section
215 if ((SecFlags & NoLoad) == 0)
217 if (!ReadOnlyRemoved)
221 case 'y': // not readable
222 SecFlags |= NoRead | NoWrite;
226 return TokError("unknown flag");
232 if (SecFlags == None)
236 *Flags |= COFF::IMAGE_SCN_CNT_CODE | COFF::IMAGE_SCN_MEM_EXECUTE;
237 if (SecFlags & InitData)
238 *Flags |= COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
239 if ((SecFlags & Alloc) && (SecFlags & Load) == 0)
240 *Flags |= COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
241 if (SecFlags & NoLoad)
242 *Flags |= COFF::IMAGE_SCN_LNK_REMOVE;
243 if ((SecFlags & NoRead) == 0)
244 *Flags |= COFF::IMAGE_SCN_MEM_READ;
245 if ((SecFlags & NoWrite) == 0)
246 *Flags |= COFF::IMAGE_SCN_MEM_WRITE;
247 if (SecFlags & Shared)
248 *Flags |= COFF::IMAGE_SCN_MEM_SHARED;
253 /// ParseDirectiveSymbolAttribute
254 /// ::= { ".weak", ... } [ identifier ( , identifier )* ]
255 bool COFFAsmParser::ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc) {
256 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Directive)
257 .Case(".weak", MCSA_Weak)
258 .Default(MCSA_Invalid);
259 assert(Attr != MCSA_Invalid && "unexpected symbol attribute directive!");
260 if (getLexer().isNot(AsmToken::EndOfStatement)) {
264 if (getParser().parseIdentifier(Name))
265 return TokError("expected identifier in directive");
267 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
269 getStreamer().EmitSymbolAttribute(Sym, Attr);
271 if (getLexer().is(AsmToken::EndOfStatement))
274 if (getLexer().isNot(AsmToken::Comma))
275 return TokError("unexpected token in directive");
284 bool COFFAsmParser::ParseSectionSwitch(StringRef Section,
285 unsigned Characteristics,
287 if (getLexer().isNot(AsmToken::EndOfStatement))
288 return TokError("unexpected token in section switching directive");
291 getStreamer().SwitchSection(getContext().getCOFFSection(
292 Section, Characteristics, Kind));
297 bool COFFAsmParser::ParseSectionName(StringRef &SectionName) {
298 return getParser().parseIdentifier(SectionName);
301 // .section name [, "flags"]
305 // b: BSS section (uninitialized data)
306 // d: data section (initialized data)
307 // n: Discardable section
308 // r: Readable section
310 // w: Writable section
311 // x: Executable section
312 // y: Not-readable section (clears 'r')
314 // Subsections are not supported.
315 bool COFFAsmParser::ParseDirectiveSection(StringRef, SMLoc) {
316 StringRef SectionName;
318 if (ParseSectionName(SectionName))
319 return TokError("expected identifier in directive");
321 unsigned Flags = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
322 COFF::IMAGE_SCN_MEM_READ |
323 COFF::IMAGE_SCN_MEM_WRITE;
325 if (getLexer().is(AsmToken::Comma)) {
328 if (getLexer().isNot(AsmToken::String))
329 return TokError("expected string in directive");
331 StringRef FlagsStr = getTok().getStringContents();
334 if (ParseSectionFlags(FlagsStr, &Flags))
338 if (getLexer().isNot(AsmToken::EndOfStatement))
339 return TokError("unexpected token in directive");
341 SectionKind Kind = computeSectionKind(Flags);
342 ParseSectionSwitch(SectionName, Flags, Kind);
346 bool COFFAsmParser::ParseDirectiveDef(StringRef, SMLoc) {
347 StringRef SymbolName;
349 if (getParser().parseIdentifier(SymbolName))
350 return TokError("expected identifier in directive");
352 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
354 getStreamer().BeginCOFFSymbolDef(Sym);
360 bool COFFAsmParser::ParseDirectiveScl(StringRef, SMLoc) {
361 int64_t SymbolStorageClass;
362 if (getParser().parseAbsoluteExpression(SymbolStorageClass))
365 if (getLexer().isNot(AsmToken::EndOfStatement))
366 return TokError("unexpected token in directive");
369 getStreamer().EmitCOFFSymbolStorageClass(SymbolStorageClass);
373 bool COFFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
375 if (getParser().parseAbsoluteExpression(Type))
378 if (getLexer().isNot(AsmToken::EndOfStatement))
379 return TokError("unexpected token in directive");
382 getStreamer().EmitCOFFSymbolType(Type);
386 bool COFFAsmParser::ParseDirectiveEndef(StringRef, SMLoc) {
388 getStreamer().EndCOFFSymbolDef();
392 bool COFFAsmParser::ParseDirectiveSecRel32(StringRef, SMLoc) {
394 if (getParser().parseIdentifier(SymbolID))
397 if (getLexer().isNot(AsmToken::EndOfStatement))
398 return TokError("unexpected token in directive");
400 MCSymbol *Symbol = getContext().GetOrCreateSymbol(SymbolID);
403 getStreamer().EmitCOFFSecRel32(Symbol);
407 /// ParseDirectiveLinkOnce
408 /// ::= .linkonce [ identifier [ identifier ] ]
409 bool COFFAsmParser::ParseDirectiveLinkOnce(StringRef, SMLoc Loc) {
410 COFF::COMDATType Type = COFF::IMAGE_COMDAT_SELECT_ANY;
412 if (getLexer().is(AsmToken::Identifier)) {
413 StringRef TypeId = getTok().getIdentifier();
415 Type = StringSwitch<COFF::COMDATType>(TypeId)
416 .Case("one_only", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES)
417 .Case("discard", COFF::IMAGE_COMDAT_SELECT_ANY)
418 .Case("same_size", COFF::IMAGE_COMDAT_SELECT_SAME_SIZE)
419 .Case("same_contents", COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH)
420 .Case("associative", COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
421 .Case("largest", COFF::IMAGE_COMDAT_SELECT_LARGEST)
422 .Case("newest", COFF::IMAGE_COMDAT_SELECT_NEWEST)
423 .Default((COFF::COMDATType)0);
426 return TokError(Twine("unrecognized COMDAT type '" + TypeId + "'"));
431 const MCSectionCOFF *Current = static_cast<const MCSectionCOFF*>(
432 getStreamer().getCurrentSection().first);
434 const MCSectionCOFF *Assoc = 0;
435 if (Type == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
437 SMLoc Loc = getTok().getLoc();
438 if (ParseSectionName(AssocName))
439 return TokError("expected associated section name");
441 Assoc = static_cast<const MCSectionCOFF*>(
442 getContext().getCOFFSection(AssocName));
444 return Error(Loc, "cannot associate unknown section '" + AssocName + "'");
445 if (Assoc == Current)
446 return Error(Loc, "cannot associate a section with itself");
447 if (!(Assoc->getCharacteristics() & COFF::IMAGE_SCN_LNK_COMDAT))
448 return Error(Loc, "associated section must be a COMDAT section");
449 if (Assoc->getSelection() == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
450 return Error(Loc, "associated section cannot be itself associative");
453 if (Current->getCharacteristics() & COFF::IMAGE_SCN_LNK_COMDAT)
454 return Error(Loc, Twine("section '") + Current->getSectionName() +
455 "' is already linkonce");
457 Current->setSelection(Type, Assoc);
459 if (getLexer().isNot(AsmToken::EndOfStatement))
460 return TokError("unexpected token in directive");
465 bool COFFAsmParser::ParseSEHDirectiveStartProc(StringRef, SMLoc) {
467 if (getParser().parseIdentifier(SymbolID))
470 if (getLexer().isNot(AsmToken::EndOfStatement))
471 return TokError("unexpected token in directive");
473 MCSymbol *Symbol = getContext().GetOrCreateSymbol(SymbolID);
476 getStreamer().EmitWin64EHStartProc(Symbol);
480 bool COFFAsmParser::ParseSEHDirectiveEndProc(StringRef, SMLoc) {
482 getStreamer().EmitWin64EHEndProc();
486 bool COFFAsmParser::ParseSEHDirectiveStartChained(StringRef, SMLoc) {
488 getStreamer().EmitWin64EHStartChained();
492 bool COFFAsmParser::ParseSEHDirectiveEndChained(StringRef, SMLoc) {
494 getStreamer().EmitWin64EHEndChained();
498 bool COFFAsmParser::ParseSEHDirectiveHandler(StringRef, SMLoc) {
500 if (getParser().parseIdentifier(SymbolID))
503 if (getLexer().isNot(AsmToken::Comma))
504 return TokError("you must specify one or both of @unwind or @except");
506 bool unwind = false, except = false;
507 if (ParseAtUnwindOrAtExcept(unwind, except))
509 if (getLexer().is(AsmToken::Comma)) {
511 if (ParseAtUnwindOrAtExcept(unwind, except))
514 if (getLexer().isNot(AsmToken::EndOfStatement))
515 return TokError("unexpected token in directive");
517 MCSymbol *handler = getContext().GetOrCreateSymbol(SymbolID);
520 getStreamer().EmitWin64EHHandler(handler, unwind, except);
524 bool COFFAsmParser::ParseSEHDirectiveHandlerData(StringRef, SMLoc) {
526 getStreamer().EmitWin64EHHandlerData();
530 bool COFFAsmParser::ParseSEHDirectivePushReg(StringRef, SMLoc L) {
532 if (ParseSEHRegisterNumber(Reg))
535 if (getLexer().isNot(AsmToken::EndOfStatement))
536 return TokError("unexpected token in directive");
539 getStreamer().EmitWin64EHPushReg(Reg);
543 bool COFFAsmParser::ParseSEHDirectiveSetFrame(StringRef, SMLoc L) {
546 if (ParseSEHRegisterNumber(Reg))
548 if (getLexer().isNot(AsmToken::Comma))
549 return TokError("you must specify a stack pointer offset");
552 SMLoc startLoc = getLexer().getLoc();
553 if (getParser().parseAbsoluteExpression(Off))
557 return Error(startLoc, "offset is not a multiple of 16");
559 if (getLexer().isNot(AsmToken::EndOfStatement))
560 return TokError("unexpected token in directive");
563 getStreamer().EmitWin64EHSetFrame(Reg, Off);
567 bool COFFAsmParser::ParseSEHDirectiveAllocStack(StringRef, SMLoc) {
569 SMLoc startLoc = getLexer().getLoc();
570 if (getParser().parseAbsoluteExpression(Size))
574 return Error(startLoc, "size is not a multiple of 8");
576 if (getLexer().isNot(AsmToken::EndOfStatement))
577 return TokError("unexpected token in directive");
580 getStreamer().EmitWin64EHAllocStack(Size);
584 bool COFFAsmParser::ParseSEHDirectiveSaveReg(StringRef, SMLoc L) {
587 if (ParseSEHRegisterNumber(Reg))
589 if (getLexer().isNot(AsmToken::Comma))
590 return TokError("you must specify an offset on the stack");
593 SMLoc startLoc = getLexer().getLoc();
594 if (getParser().parseAbsoluteExpression(Off))
598 return Error(startLoc, "size is not a multiple of 8");
600 if (getLexer().isNot(AsmToken::EndOfStatement))
601 return TokError("unexpected token in directive");
604 // FIXME: Err on %xmm* registers
605 getStreamer().EmitWin64EHSaveReg(Reg, Off);
609 // FIXME: This method is inherently x86-specific. It should really be in the
611 bool COFFAsmParser::ParseSEHDirectiveSaveXMM(StringRef, SMLoc L) {
614 if (ParseSEHRegisterNumber(Reg))
616 if (getLexer().isNot(AsmToken::Comma))
617 return TokError("you must specify an offset on the stack");
620 SMLoc startLoc = getLexer().getLoc();
621 if (getParser().parseAbsoluteExpression(Off))
624 if (getLexer().isNot(AsmToken::EndOfStatement))
625 return TokError("unexpected token in directive");
628 return Error(startLoc, "offset is not a multiple of 16");
631 // FIXME: Err on non-%xmm* registers
632 getStreamer().EmitWin64EHSaveXMM(Reg, Off);
636 bool COFFAsmParser::ParseSEHDirectivePushFrame(StringRef, SMLoc) {
639 if (getLexer().is(AsmToken::At)) {
640 SMLoc startLoc = getLexer().getLoc();
642 if (!getParser().parseIdentifier(CodeID)) {
643 if (CodeID != "code")
644 return Error(startLoc, "expected @code");
649 if (getLexer().isNot(AsmToken::EndOfStatement))
650 return TokError("unexpected token in directive");
653 getStreamer().EmitWin64EHPushFrame(Code);
657 bool COFFAsmParser::ParseSEHDirectiveEndProlog(StringRef, SMLoc) {
659 getStreamer().EmitWin64EHEndProlog();
663 bool COFFAsmParser::ParseAtUnwindOrAtExcept(bool &unwind, bool &except) {
664 StringRef identifier;
665 if (getLexer().isNot(AsmToken::At))
666 return TokError("a handler attribute must begin with '@'");
667 SMLoc startLoc = getLexer().getLoc();
669 if (getParser().parseIdentifier(identifier))
670 return Error(startLoc, "expected @unwind or @except");
671 if (identifier == "unwind")
673 else if (identifier == "except")
676 return Error(startLoc, "expected @unwind or @except");
680 bool COFFAsmParser::ParseSEHRegisterNumber(unsigned &RegNo) {
681 SMLoc startLoc = getLexer().getLoc();
682 if (getLexer().is(AsmToken::Percent)) {
683 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
686 if (getParser().getTargetParser().ParseRegister(LLVMRegNo,startLoc,endLoc))
690 // FIXME: TargetAsmInfo::getCalleeSavedRegs() commits a serious layering
691 // violation so this validation code is disabled.
693 // Check that this is a non-volatile register.
694 const unsigned *NVRegs = TAI.getCalleeSavedRegs();
696 for (i = 0; NVRegs[i] != 0; ++i)
697 if (NVRegs[i] == LLVMRegNo)
700 return Error(startLoc, "expected non-volatile register");
703 int SEHRegNo = MRI->getSEHRegNum(LLVMRegNo);
705 return Error(startLoc,"register can't be represented in SEH unwind info");
710 if (getParser().parseAbsoluteExpression(n))
713 return Error(startLoc, "register number is too high");
722 MCAsmParserExtension *createCOFFAsmParser() {
723 return new COFFAsmParser;