4b519dd7c97812cbbc1dbcf92580e0415fe72580
[oota-llvm.git] / include / llvm / MC / MCAssembler.h
1 //===- MCAssembler.h - Object File Generation -------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_MC_MCASSEMBLER_H
11 #define LLVM_MC_MCASSEMBLER_H
12
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/ilist.h"
17 #include "llvm/ADT/ilist_node.h"
18 #include "llvm/MC/MCDirectives.h"
19 #include "llvm/MC/MCFixup.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCSubtargetInfo.h"
22 #include "llvm/Support/Casting.h"
23 #include "llvm/Support/DataTypes.h"
24 #include <algorithm>
25 #include <vector> // FIXME: Shouldn't be needed.
26
27 namespace llvm {
28 class raw_ostream;
29 class MCAsmLayout;
30 class MCAssembler;
31 class MCContext;
32 class MCCodeEmitter;
33 class MCExpr;
34 class MCFragment;
35 class MCObjectWriter;
36 class MCSection;
37 class MCSectionData;
38 class MCSubtargetInfo;
39 class MCSymbol;
40 class MCSymbolData;
41 class MCValue;
42 class MCAsmBackend;
43
44 class MCFragment : public ilist_node<MCFragment> {
45   friend class MCAsmLayout;
46
47   MCFragment(const MCFragment&) LLVM_DELETED_FUNCTION;
48   void operator=(const MCFragment&) LLVM_DELETED_FUNCTION;
49
50 public:
51   enum FragmentType {
52     FT_Align,
53     FT_Data,
54     FT_CompactEncodedInst,
55     FT_Fill,
56     FT_Relaxable,
57     FT_Org,
58     FT_Dwarf,
59     FT_DwarfFrame,
60     FT_LEB
61   };
62
63 private:
64   FragmentType Kind;
65
66   /// Parent - The data for the section this fragment is in.
67   MCSectionData *Parent;
68
69   /// Atom - The atom this fragment is in, as represented by it's defining
70   /// symbol.
71   MCSymbolData *Atom;
72
73   /// @name Assembler Backend Data
74   /// @{
75   //
76   // FIXME: This could all be kept private to the assembler implementation.
77
78   /// Offset - The offset of this fragment in its section. This is ~0 until
79   /// initialized.
80   uint64_t Offset;
81
82   /// LayoutOrder - The layout order of this fragment.
83   unsigned LayoutOrder;
84
85   /// @}
86
87 protected:
88   MCFragment(FragmentType _Kind, MCSectionData *_Parent = 0);
89
90 public:
91   // Only for sentinel.
92   MCFragment();
93   virtual ~MCFragment();
94
95   FragmentType getKind() const { return Kind; }
96
97   MCSectionData *getParent() const { return Parent; }
98   void setParent(MCSectionData *Value) { Parent = Value; }
99
100   MCSymbolData *getAtom() const { return Atom; }
101   void setAtom(MCSymbolData *Value) { Atom = Value; }
102
103   unsigned getLayoutOrder() const { return LayoutOrder; }
104   void setLayoutOrder(unsigned Value) { LayoutOrder = Value; }
105
106   /// \brief Does this fragment have instructions emitted into it? By default
107   /// this is false, but specific fragment types may set it to true.
108   virtual bool hasInstructions() const { return false; }
109
110   /// \brief Should this fragment be placed at the end of an aligned bundle?
111   virtual bool alignToBundleEnd() const { return false; }
112   virtual void setAlignToBundleEnd(bool V) { }
113
114   /// \brief Get the padding size that must be inserted before this fragment.
115   /// Used for bundling. By default, no padding is inserted.
116   /// Note that padding size is restricted to 8 bits. This is an optimization
117   /// to reduce the amount of space used for each fragment. In practice, larger
118   /// padding should never be required.
119   virtual uint8_t getBundlePadding() const {
120     return 0;
121   }
122
123   /// \brief Set the padding size for this fragment. By default it's a no-op,
124   /// and only some fragments have a meaningful implementation.
125   virtual void setBundlePadding(uint8_t N) {
126   }
127
128   void dump();
129 };
130
131 /// Interface implemented by fragments that contain encoded instructions and/or
132 /// data.
133 ///
134 class MCEncodedFragment : public MCFragment {
135   virtual void anchor();
136
137   uint8_t BundlePadding;
138 public:
139   MCEncodedFragment(MCFragment::FragmentType FType, MCSectionData *SD = 0)
140     : MCFragment(FType, SD), BundlePadding(0)
141   {
142   }
143   virtual ~MCEncodedFragment();
144
145   virtual SmallVectorImpl<char> &getContents() = 0;
146   virtual const SmallVectorImpl<char> &getContents() const = 0;
147
148   uint8_t getBundlePadding() const override {
149     return BundlePadding;
150   }
151
152   void setBundlePadding(uint8_t N) override {
153     BundlePadding = N;
154   }
155
156   static bool classof(const MCFragment *F) {
157     MCFragment::FragmentType Kind = F->getKind();
158     switch (Kind) {
159       default:
160         return false;
161       case MCFragment::FT_Relaxable:
162       case MCFragment::FT_CompactEncodedInst:
163       case MCFragment::FT_Data:
164         return true;
165     }
166   }
167 };
168
169 /// Interface implemented by fragments that contain encoded instructions and/or
170 /// data and also have fixups registered.
171 ///
172 class MCEncodedFragmentWithFixups : public MCEncodedFragment {
173   void anchor() override;
174
175 public:
176   MCEncodedFragmentWithFixups(MCFragment::FragmentType FType,
177                               MCSectionData *SD = 0)
178     : MCEncodedFragment(FType, SD)
179   {
180   }
181
182   virtual ~MCEncodedFragmentWithFixups();
183
184   typedef SmallVectorImpl<MCFixup>::const_iterator const_fixup_iterator;
185   typedef SmallVectorImpl<MCFixup>::iterator fixup_iterator;
186
187   virtual SmallVectorImpl<MCFixup> &getFixups() = 0;
188   virtual const SmallVectorImpl<MCFixup> &getFixups() const = 0;
189
190   virtual fixup_iterator fixup_begin() = 0;
191   virtual const_fixup_iterator fixup_begin() const  = 0;
192   virtual fixup_iterator fixup_end() = 0;
193   virtual const_fixup_iterator fixup_end() const = 0;
194
195   static bool classof(const MCFragment *F) {
196     MCFragment::FragmentType Kind = F->getKind();
197     return Kind == MCFragment::FT_Relaxable || Kind == MCFragment::FT_Data;
198   }
199 };
200
201 /// Fragment for data and encoded instructions.
202 ///
203 class MCDataFragment : public MCEncodedFragmentWithFixups {
204   void anchor() override;
205
206   /// \brief Does this fragment contain encoded instructions anywhere in it?
207   bool HasInstructions;
208
209   /// \brief Should this fragment be aligned to the end of a bundle?
210   bool AlignToBundleEnd;
211
212   SmallVector<char, 32> Contents;
213
214   /// Fixups - The list of fixups in this fragment.
215   SmallVector<MCFixup, 4> Fixups;
216 public:
217   MCDataFragment(MCSectionData *SD = 0)
218     : MCEncodedFragmentWithFixups(FT_Data, SD),
219       HasInstructions(false), AlignToBundleEnd(false)
220   {
221   }
222
223   SmallVectorImpl<char> &getContents() override { return Contents; }
224   const SmallVectorImpl<char> &getContents() const override {
225     return Contents;
226   }
227
228   SmallVectorImpl<MCFixup> &getFixups() override {
229     return Fixups;
230   }
231
232   const SmallVectorImpl<MCFixup> &getFixups() const override {
233     return Fixups;
234   }
235
236   bool hasInstructions() const override { return HasInstructions; }
237   virtual void setHasInstructions(bool V) { HasInstructions = V; }
238
239   bool alignToBundleEnd() const override { return AlignToBundleEnd; }
240   void setAlignToBundleEnd(bool V) override { AlignToBundleEnd = V; }
241
242   fixup_iterator fixup_begin() override { return Fixups.begin(); }
243   const_fixup_iterator fixup_begin() const override { return Fixups.begin(); }
244
245   fixup_iterator fixup_end() override {return Fixups.end();}
246   const_fixup_iterator fixup_end() const override {return Fixups.end();}
247
248   static bool classof(const MCFragment *F) {
249     return F->getKind() == MCFragment::FT_Data;
250   }
251 };
252
253 /// This is a compact (memory-size-wise) fragment for holding an encoded
254 /// instruction (non-relaxable) that has no fixups registered. When applicable,
255 /// it can be used instead of MCDataFragment and lead to lower memory
256 /// consumption.
257 ///
258 class MCCompactEncodedInstFragment : public MCEncodedFragment {
259   void anchor() override;
260
261   /// \brief Should this fragment be aligned to the end of a bundle?
262   bool AlignToBundleEnd;
263
264   SmallVector<char, 4> Contents;
265 public:
266   MCCompactEncodedInstFragment(MCSectionData *SD = 0)
267     : MCEncodedFragment(FT_CompactEncodedInst, SD), AlignToBundleEnd(false)
268   {
269   }
270
271   bool hasInstructions() const override {
272     return true;
273   }
274
275   SmallVectorImpl<char> &getContents() override { return Contents; }
276   const SmallVectorImpl<char> &getContents() const override { return Contents; }
277
278   bool alignToBundleEnd() const override { return AlignToBundleEnd; }
279   void setAlignToBundleEnd(bool V) override { AlignToBundleEnd = V; }
280
281   static bool classof(const MCFragment *F) {
282     return F->getKind() == MCFragment::FT_CompactEncodedInst;
283   }
284 };
285
286 /// A relaxable fragment holds on to its MCInst, since it may need to be
287 /// relaxed during the assembler layout and relaxation stage.
288 ///
289 class MCRelaxableFragment : public MCEncodedFragmentWithFixups {
290   void anchor() override;
291
292   /// Inst - The instruction this is a fragment for.
293   MCInst Inst;
294
295   /// STI - The MCSubtargetInfo in effect when the instruction was encoded.
296   /// Keep a copy instead of a reference to make sure that updates to STI
297   /// in the assembler are not seen here.
298   const MCSubtargetInfo STI;
299
300   /// Contents - Binary data for the currently encoded instruction.
301   SmallVector<char, 8> Contents;
302
303   /// Fixups - The list of fixups in this fragment.
304   SmallVector<MCFixup, 1> Fixups;
305
306 public:
307   MCRelaxableFragment(const MCInst &_Inst,
308                       const MCSubtargetInfo &_STI,
309                       MCSectionData *SD = 0)
310     : MCEncodedFragmentWithFixups(FT_Relaxable, SD), Inst(_Inst), STI(_STI) {
311   }
312
313   SmallVectorImpl<char> &getContents() override { return Contents; }
314   const SmallVectorImpl<char> &getContents() const override { return Contents; }
315
316   const MCInst &getInst() const { return Inst; }
317   void setInst(const MCInst& Value) { Inst = Value; }
318
319   const MCSubtargetInfo &getSubtargetInfo() { return STI; }
320
321   SmallVectorImpl<MCFixup> &getFixups() override {
322     return Fixups;
323   }
324
325   const SmallVectorImpl<MCFixup> &getFixups() const override {
326     return Fixups;
327   }
328
329   bool hasInstructions() const override { return true; }
330
331   fixup_iterator fixup_begin() override { return Fixups.begin(); }
332   const_fixup_iterator fixup_begin() const override { return Fixups.begin(); }
333
334   fixup_iterator fixup_end() override {return Fixups.end();}
335   const_fixup_iterator fixup_end() const override {return Fixups.end();}
336
337   static bool classof(const MCFragment *F) {
338     return F->getKind() == MCFragment::FT_Relaxable;
339   }
340 };
341
342 class MCAlignFragment : public MCFragment {
343   virtual void anchor();
344
345   /// Alignment - The alignment to ensure, in bytes.
346   unsigned Alignment;
347
348   /// Value - Value to use for filling padding bytes.
349   int64_t Value;
350
351   /// ValueSize - The size of the integer (in bytes) of \p Value.
352   unsigned ValueSize;
353
354   /// MaxBytesToEmit - The maximum number of bytes to emit; if the alignment
355   /// cannot be satisfied in this width then this fragment is ignored.
356   unsigned MaxBytesToEmit;
357
358   /// EmitNops - Flag to indicate that (optimal) NOPs should be emitted instead
359   /// of using the provided value. The exact interpretation of this flag is
360   /// target dependent.
361   bool EmitNops : 1;
362
363 public:
364   MCAlignFragment(unsigned _Alignment, int64_t _Value, unsigned _ValueSize,
365                   unsigned _MaxBytesToEmit, MCSectionData *SD = 0)
366     : MCFragment(FT_Align, SD), Alignment(_Alignment),
367       Value(_Value),ValueSize(_ValueSize),
368       MaxBytesToEmit(_MaxBytesToEmit), EmitNops(false) {}
369
370   /// @name Accessors
371   /// @{
372
373   unsigned getAlignment() const { return Alignment; }
374
375   int64_t getValue() const { return Value; }
376
377   unsigned getValueSize() const { return ValueSize; }
378
379   unsigned getMaxBytesToEmit() const { return MaxBytesToEmit; }
380
381   bool hasEmitNops() const { return EmitNops; }
382   void setEmitNops(bool Value) { EmitNops = Value; }
383
384   /// @}
385
386   static bool classof(const MCFragment *F) {
387     return F->getKind() == MCFragment::FT_Align;
388   }
389 };
390
391 class MCFillFragment : public MCFragment {
392   virtual void anchor();
393
394   /// Value - Value to use for filling bytes.
395   int64_t Value;
396
397   /// ValueSize - The size (in bytes) of \p Value to use when filling, or 0 if
398   /// this is a virtual fill fragment.
399   unsigned ValueSize;
400
401   /// Size - The number of bytes to insert.
402   uint64_t Size;
403
404 public:
405   MCFillFragment(int64_t _Value, unsigned _ValueSize, uint64_t _Size,
406                  MCSectionData *SD = 0)
407     : MCFragment(FT_Fill, SD),
408       Value(_Value), ValueSize(_ValueSize), Size(_Size) {
409     assert((!ValueSize || (Size % ValueSize) == 0) &&
410            "Fill size must be a multiple of the value size!");
411   }
412
413   /// @name Accessors
414   /// @{
415
416   int64_t getValue() const { return Value; }
417
418   unsigned getValueSize() const { return ValueSize; }
419
420   uint64_t getSize() const { return Size; }
421
422   /// @}
423
424   static bool classof(const MCFragment *F) {
425     return F->getKind() == MCFragment::FT_Fill;
426   }
427 };
428
429 class MCOrgFragment : public MCFragment {
430   virtual void anchor();
431
432   /// Offset - The offset this fragment should start at.
433   const MCExpr *Offset;
434
435   /// Value - Value to use for filling bytes.
436   int8_t Value;
437
438 public:
439   MCOrgFragment(const MCExpr &_Offset, int8_t _Value, MCSectionData *SD = 0)
440     : MCFragment(FT_Org, SD),
441       Offset(&_Offset), Value(_Value) {}
442
443   /// @name Accessors
444   /// @{
445
446   const MCExpr &getOffset() const { return *Offset; }
447
448   uint8_t getValue() const { return Value; }
449
450   /// @}
451
452   static bool classof(const MCFragment *F) {
453     return F->getKind() == MCFragment::FT_Org;
454   }
455 };
456
457 class MCLEBFragment : public MCFragment {
458   virtual void anchor();
459
460   /// Value - The value this fragment should contain.
461   const MCExpr *Value;
462
463   /// IsSigned - True if this is a sleb128, false if uleb128.
464   bool IsSigned;
465
466   SmallString<8> Contents;
467 public:
468   MCLEBFragment(const MCExpr &Value_, bool IsSigned_, MCSectionData *SD = 0)
469     : MCFragment(FT_LEB, SD),
470       Value(&Value_), IsSigned(IsSigned_) { Contents.push_back(0); }
471
472   /// @name Accessors
473   /// @{
474
475   const MCExpr &getValue() const { return *Value; }
476
477   bool isSigned() const { return IsSigned; }
478
479   SmallString<8> &getContents() { return Contents; }
480   const SmallString<8> &getContents() const { return Contents; }
481
482   /// @}
483
484   static bool classof(const MCFragment *F) {
485     return F->getKind() == MCFragment::FT_LEB;
486   }
487 };
488
489 class MCDwarfLineAddrFragment : public MCFragment {
490   virtual void anchor();
491
492   /// LineDelta - the value of the difference between the two line numbers
493   /// between two .loc dwarf directives.
494   int64_t LineDelta;
495
496   /// AddrDelta - The expression for the difference of the two symbols that
497   /// make up the address delta between two .loc dwarf directives.
498   const MCExpr *AddrDelta;
499
500   SmallString<8> Contents;
501
502 public:
503   MCDwarfLineAddrFragment(int64_t _LineDelta, const MCExpr &_AddrDelta,
504                       MCSectionData *SD = 0)
505     : MCFragment(FT_Dwarf, SD),
506       LineDelta(_LineDelta), AddrDelta(&_AddrDelta) { Contents.push_back(0); }
507
508   /// @name Accessors
509   /// @{
510
511   int64_t getLineDelta() const { return LineDelta; }
512
513   const MCExpr &getAddrDelta() const { return *AddrDelta; }
514
515   SmallString<8> &getContents() { return Contents; }
516   const SmallString<8> &getContents() const { return Contents; }
517
518   /// @}
519
520   static bool classof(const MCFragment *F) {
521     return F->getKind() == MCFragment::FT_Dwarf;
522   }
523 };
524
525 class MCDwarfCallFrameFragment : public MCFragment {
526   virtual void anchor();
527
528   /// AddrDelta - The expression for the difference of the two symbols that
529   /// make up the address delta between two .cfi_* dwarf directives.
530   const MCExpr *AddrDelta;
531
532   SmallString<8> Contents;
533
534 public:
535   MCDwarfCallFrameFragment(const MCExpr &_AddrDelta,  MCSectionData *SD = 0)
536     : MCFragment(FT_DwarfFrame, SD),
537       AddrDelta(&_AddrDelta) { Contents.push_back(0); }
538
539   /// @name Accessors
540   /// @{
541
542   const MCExpr &getAddrDelta() const { return *AddrDelta; }
543
544   SmallString<8> &getContents() { return Contents; }
545   const SmallString<8> &getContents() const { return Contents; }
546
547   /// @}
548
549   static bool classof(const MCFragment *F) {
550     return F->getKind() == MCFragment::FT_DwarfFrame;
551   }
552 };
553
554 // FIXME: Should this be a separate class, or just merged into MCSection? Since
555 // we anticipate the fast path being through an MCAssembler, the only reason to
556 // keep it out is for API abstraction.
557 class MCSectionData : public ilist_node<MCSectionData> {
558   friend class MCAsmLayout;
559
560   MCSectionData(const MCSectionData&) LLVM_DELETED_FUNCTION;
561   void operator=(const MCSectionData&) LLVM_DELETED_FUNCTION;
562
563 public:
564   typedef iplist<MCFragment> FragmentListType;
565
566   typedef FragmentListType::const_iterator const_iterator;
567   typedef FragmentListType::iterator iterator;
568
569   typedef FragmentListType::const_reverse_iterator const_reverse_iterator;
570   typedef FragmentListType::reverse_iterator reverse_iterator;
571
572   /// \brief Express the state of bundle locked groups while emitting code.
573   enum BundleLockStateType {
574     NotBundleLocked,
575     BundleLocked,
576     BundleLockedAlignToEnd
577   };
578 private:
579   FragmentListType Fragments;
580   const MCSection *Section;
581
582   /// Ordinal - The section index in the assemblers section list.
583   unsigned Ordinal;
584
585   /// LayoutOrder - The index of this section in the layout order.
586   unsigned LayoutOrder;
587
588   /// Alignment - The maximum alignment seen in this section.
589   unsigned Alignment;
590
591   /// \brief Keeping track of bundle-locked state.
592   BundleLockStateType BundleLockState; 
593
594   /// \brief We've seen a bundle_lock directive but not its first instruction
595   /// yet.
596   bool BundleGroupBeforeFirstInst;
597
598   /// @name Assembler Backend Data
599   /// @{
600   //
601   // FIXME: This could all be kept private to the assembler implementation.
602
603   /// HasInstructions - Whether this section has had instructions emitted into
604   /// it.
605   unsigned HasInstructions : 1;
606
607   /// Mapping from subsection number to insertion point for subsection numbers
608   /// below that number.
609   SmallVector<std::pair<unsigned, MCFragment *>, 1> SubsectionFragmentMap;
610
611   /// @}
612
613 public:
614   // Only for use as sentinel.
615   MCSectionData();
616   MCSectionData(const MCSection &Section, MCAssembler *A = 0);
617
618   const MCSection &getSection() const { return *Section; }
619
620   unsigned getAlignment() const { return Alignment; }
621   void setAlignment(unsigned Value) { Alignment = Value; }
622
623   bool hasInstructions() const { return HasInstructions; }
624   void setHasInstructions(bool Value) { HasInstructions = Value; }
625
626   unsigned getOrdinal() const { return Ordinal; }
627   void setOrdinal(unsigned Value) { Ordinal = Value; }
628
629   unsigned getLayoutOrder() const { return LayoutOrder; }
630   void setLayoutOrder(unsigned Value) { LayoutOrder = Value; }
631
632   /// @name Fragment Access
633   /// @{
634
635   const FragmentListType &getFragmentList() const { return Fragments; }
636   FragmentListType &getFragmentList() { return Fragments; }
637
638   iterator begin() { return Fragments.begin(); }
639   const_iterator begin() const { return Fragments.begin(); }
640
641   iterator end() { return Fragments.end(); }
642   const_iterator end() const { return Fragments.end(); }
643
644   reverse_iterator rbegin() { return Fragments.rbegin(); }
645   const_reverse_iterator rbegin() const { return Fragments.rbegin(); }
646
647   reverse_iterator rend() { return Fragments.rend(); }
648   const_reverse_iterator rend() const { return Fragments.rend(); }
649
650   size_t size() const { return Fragments.size(); }
651
652   bool empty() const { return Fragments.empty(); }
653
654   iterator getSubsectionInsertionPoint(unsigned Subsection);
655
656   bool isBundleLocked() const {
657     return BundleLockState != NotBundleLocked;
658   }
659
660   BundleLockStateType getBundleLockState() const {
661     return BundleLockState;
662   }
663
664   void setBundleLockState(BundleLockStateType NewState) {
665     BundleLockState = NewState;
666   }
667
668   bool isBundleGroupBeforeFirstInst() const {
669     return BundleGroupBeforeFirstInst;
670   }
671
672   void setBundleGroupBeforeFirstInst(bool IsFirst) {
673     BundleGroupBeforeFirstInst = IsFirst;
674   }
675
676   void dump();
677
678   /// @}
679 };
680
681 // FIXME: Same concerns as with SectionData.
682 class MCSymbolData : public ilist_node<MCSymbolData> {
683 public:
684   const MCSymbol *Symbol;
685
686   /// Fragment - The fragment this symbol's value is relative to, if any.
687   MCFragment *Fragment;
688
689   /// Offset - The offset to apply to the fragment address to form this symbol's
690   /// value.
691   uint64_t Offset;
692
693   /// IsExternal - True if this symbol is visible outside this translation
694   /// unit.
695   unsigned IsExternal : 1;
696
697   /// IsPrivateExtern - True if this symbol is private extern.
698   unsigned IsPrivateExtern : 1;
699
700   /// CommonSize - The size of the symbol, if it is 'common', or 0.
701   //
702   // FIXME: Pack this in with other fields? We could put it in offset, since a
703   // common symbol can never get a definition.
704   uint64_t CommonSize;
705
706   /// SymbolSize - An expression describing how to calculate the size of
707   /// a symbol. If a symbol has no size this field will be NULL.
708   const MCExpr *SymbolSize;
709
710   /// CommonAlign - The alignment of the symbol, if it is 'common'.
711   //
712   // FIXME: Pack this in with other fields?
713   unsigned CommonAlign;
714
715   /// Flags - The Flags field is used by object file implementations to store
716   /// additional per symbol information which is not easily classified.
717   uint32_t Flags;
718
719   /// Index - Index field, for use by the object file implementation.
720   uint64_t Index;
721
722 public:
723   // Only for use as sentinel.
724   MCSymbolData();
725   MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment, uint64_t _Offset,
726                MCAssembler *A = 0);
727
728   /// @name Accessors
729   /// @{
730
731   const MCSymbol &getSymbol() const { return *Symbol; }
732
733   MCFragment *getFragment() const { return Fragment; }
734   void setFragment(MCFragment *Value) { Fragment = Value; }
735
736   uint64_t getOffset() const { return Offset; }
737   void setOffset(uint64_t Value) { Offset = Value; }
738
739   /// @}
740   /// @name Symbol Attributes
741   /// @{
742
743   bool isExternal() const { return IsExternal; }
744   void setExternal(bool Value) { IsExternal = Value; }
745
746   bool isPrivateExtern() const { return IsPrivateExtern; }
747   void setPrivateExtern(bool Value) { IsPrivateExtern = Value; }
748
749   /// isCommon - Is this a 'common' symbol.
750   bool isCommon() const { return CommonSize != 0; }
751
752   /// setCommon - Mark this symbol as being 'common'.
753   ///
754   /// \param Size - The size of the symbol.
755   /// \param Align - The alignment of the symbol.
756   void setCommon(uint64_t Size, unsigned Align) {
757     CommonSize = Size;
758     CommonAlign = Align;
759   }
760
761   /// getCommonSize - Return the size of a 'common' symbol.
762   uint64_t getCommonSize() const {
763     assert(isCommon() && "Not a 'common' symbol!");
764     return CommonSize;
765   }
766
767   void setSize(const MCExpr *SS) {
768     SymbolSize = SS;
769   }
770
771   const MCExpr *getSize() const {
772     return SymbolSize;
773   }
774
775
776   /// getCommonAlignment - Return the alignment of a 'common' symbol.
777   unsigned getCommonAlignment() const {
778     assert(isCommon() && "Not a 'common' symbol!");
779     return CommonAlign;
780   }
781
782   /// getFlags - Get the (implementation defined) symbol flags.
783   uint32_t getFlags() const { return Flags; }
784
785   /// setFlags - Set the (implementation defined) symbol flags.
786   void setFlags(uint32_t Value) { Flags = Value; }
787
788   /// modifyFlags - Modify the flags via a mask
789   void modifyFlags(uint32_t Value, uint32_t Mask) {
790     Flags = (Flags & ~Mask) | Value;
791   }
792
793   /// getIndex - Get the (implementation defined) index.
794   uint64_t getIndex() const { return Index; }
795
796   /// setIndex - Set the (implementation defined) index.
797   void setIndex(uint64_t Value) { Index = Value; }
798
799   /// @}
800
801   void dump();
802 };
803
804 // FIXME: This really doesn't belong here. See comments below.
805 struct IndirectSymbolData {
806   MCSymbol *Symbol;
807   MCSectionData *SectionData;
808 };
809
810 // FIXME: Ditto this. Purely so the Streamer and the ObjectWriter can talk
811 // to one another.
812 struct DataRegionData {
813   // This enum should be kept in sync w/ the mach-o definition in
814   // llvm/Object/MachOFormat.h.
815   enum KindTy { Data = 1, JumpTable8, JumpTable16, JumpTable32 } Kind;
816   MCSymbol *Start;
817   MCSymbol *End;
818 };
819
820 class MCAssembler {
821   friend class MCAsmLayout;
822
823 public:
824   typedef iplist<MCSectionData> SectionDataListType;
825   typedef iplist<MCSymbolData> SymbolDataListType;
826
827   typedef SectionDataListType::const_iterator const_iterator;
828   typedef SectionDataListType::iterator iterator;
829
830   typedef SymbolDataListType::const_iterator const_symbol_iterator;
831   typedef SymbolDataListType::iterator symbol_iterator;
832
833   typedef std::vector<std::string> FileNameVectorType;
834   typedef FileNameVectorType::const_iterator const_file_name_iterator;
835
836   typedef std::vector<IndirectSymbolData>::const_iterator
837     const_indirect_symbol_iterator;
838   typedef std::vector<IndirectSymbolData>::iterator indirect_symbol_iterator;
839
840   typedef std::vector<DataRegionData>::const_iterator
841     const_data_region_iterator;
842   typedef std::vector<DataRegionData>::iterator data_region_iterator;
843
844   /// MachO specific deployment target version info.
845   // A Major version of 0 indicates that no version information was supplied
846   // and so the corresponding load command should not be emitted.
847   typedef struct {
848     MCVersionMinType Kind;
849     unsigned Major;
850     unsigned Minor;
851     unsigned Update;
852   } VersionMinInfoType;
853 private:
854   MCAssembler(const MCAssembler&) LLVM_DELETED_FUNCTION;
855   void operator=(const MCAssembler&) LLVM_DELETED_FUNCTION;
856
857   MCContext &Context;
858
859   MCAsmBackend &Backend;
860
861   MCCodeEmitter &Emitter;
862
863   MCObjectWriter &Writer;
864
865   raw_ostream &OS;
866
867   iplist<MCSectionData> Sections;
868
869   iplist<MCSymbolData> Symbols;
870
871   /// The map of sections to their associated assembler backend data.
872   //
873   // FIXME: Avoid this indirection?
874   DenseMap<const MCSection*, MCSectionData*> SectionMap;
875
876   /// The map of symbols to their associated assembler backend data.
877   //
878   // FIXME: Avoid this indirection?
879   DenseMap<const MCSymbol*, MCSymbolData*> SymbolMap;
880
881   std::vector<IndirectSymbolData> IndirectSymbols;
882
883   std::vector<DataRegionData> DataRegions;
884
885   /// The list of linker options to propagate into the object file.
886   std::vector<std::vector<std::string> > LinkerOptions;
887
888   /// List of declared file names
889   FileNameVectorType FileNames;
890
891   /// The set of function symbols for which a .thumb_func directive has
892   /// been seen.
893   //
894   // FIXME: We really would like this in target specific code rather than
895   // here. Maybe when the relocation stuff moves to target specific,
896   // this can go with it? The streamer would need some target specific
897   // refactoring too.
898   SmallPtrSet<const MCSymbol*, 64> ThumbFuncs;
899
900   /// \brief The bundle alignment size currently set in the assembler.
901   ///
902   /// By default it's 0, which means bundling is disabled.
903   unsigned BundleAlignSize;
904
905   unsigned RelaxAll : 1;
906   unsigned NoExecStack : 1;
907   unsigned SubsectionsViaSymbols : 1;
908
909   /// ELF specific e_header flags
910   // It would be good if there were an MCELFAssembler class to hold this.
911   // ELF header flags are used both by the integrated and standalone assemblers.
912   // Access to the flags is necessary in cases where assembler directives affect
913   // which flags to be set.
914   unsigned ELFHeaderEFlags;
915
916   VersionMinInfoType VersionMinInfo;
917 private:
918   /// Evaluate a fixup to a relocatable expression and the value which should be
919   /// placed into the fixup.
920   ///
921   /// \param Layout The layout to use for evaluation.
922   /// \param Fixup The fixup to evaluate.
923   /// \param DF The fragment the fixup is inside.
924   /// \param Target [out] On return, the relocatable expression the fixup
925   /// evaluates to.
926   /// \param Value [out] On return, the value of the fixup as currently laid
927   /// out.
928   /// \return Whether the fixup value was fully resolved. This is true if the
929   /// \p Value result is fixed, otherwise the value may change due to
930   /// relocation.
931   bool evaluateFixup(const MCAsmLayout &Layout,
932                      const MCFixup &Fixup, const MCFragment *DF,
933                      MCValue &Target, uint64_t &Value) const;
934
935   /// Check whether a fixup can be satisfied, or whether it needs to be relaxed
936   /// (increased in size, in order to hold its value correctly).
937   bool fixupNeedsRelaxation(const MCFixup &Fixup, const MCRelaxableFragment *DF,
938                             const MCAsmLayout &Layout) const;
939
940   /// Check whether the given fragment needs relaxation.
941   bool fragmentNeedsRelaxation(const MCRelaxableFragment *IF,
942                                const MCAsmLayout &Layout) const;
943
944   /// \brief Perform one layout iteration and return true if any offsets
945   /// were adjusted.
946   bool layoutOnce(MCAsmLayout &Layout);
947
948   /// \brief Perform one layout iteration of the given section and return true
949   /// if any offsets were adjusted.
950   bool layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD);
951
952   bool relaxInstruction(MCAsmLayout &Layout, MCRelaxableFragment &IF);
953
954   bool relaxLEB(MCAsmLayout &Layout, MCLEBFragment &IF);
955
956   bool relaxDwarfLineAddr(MCAsmLayout &Layout, MCDwarfLineAddrFragment &DF);
957   bool relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
958                                    MCDwarfCallFrameFragment &DF);
959
960   /// finishLayout - Finalize a layout, including fragment lowering.
961   void finishLayout(MCAsmLayout &Layout);
962
963   uint64_t handleFixup(const MCAsmLayout &Layout,
964                        MCFragment &F, const MCFixup &Fixup);
965
966 public:
967   /// Compute the effective fragment size assuming it is laid out at the given
968   /// \p SectionAddress and \p FragmentOffset.
969   uint64_t computeFragmentSize(const MCAsmLayout &Layout,
970                                const MCFragment &F) const;
971
972   /// Find the symbol which defines the atom containing the given symbol, or
973   /// null if there is no such symbol.
974   const MCSymbolData *getAtom(const MCSymbolData *Symbol) const;
975
976   /// Check whether a particular symbol is visible to the linker and is required
977   /// in the symbol table, or whether it can be discarded by the assembler. This
978   /// also effects whether the assembler treats the label as potentially
979   /// defining a separate atom.
980   bool isSymbolLinkerVisible(const MCSymbol &SD) const;
981
982   /// Emit the section contents using the given object writer.
983   void writeSectionData(const MCSectionData *Section,
984                         const MCAsmLayout &Layout) const;
985
986   /// Check whether a given symbol has been flagged with .thumb_func.
987   bool isThumbFunc(const MCSymbol *Func) const {
988     return ThumbFuncs.count(Func);
989   }
990
991   /// Flag a function symbol as the target of a .thumb_func directive.
992   void setIsThumbFunc(const MCSymbol *Func) { ThumbFuncs.insert(Func); }
993
994   /// ELF e_header flags
995   unsigned getELFHeaderEFlags() const {return ELFHeaderEFlags;}
996   void setELFHeaderEFlags(unsigned Flags) { ELFHeaderEFlags = Flags;}
997
998   /// MachO deployment target version information.
999   const VersionMinInfoType &getVersionMinInfo() const { return VersionMinInfo; }
1000   void setVersionMinInfo(MCVersionMinType Kind, unsigned Major, unsigned Minor,
1001                          unsigned Update) {
1002     VersionMinInfo.Kind = Kind;
1003     VersionMinInfo.Major = Major;
1004     VersionMinInfo.Minor = Minor;
1005     VersionMinInfo.Update = Update;
1006   }
1007
1008 public:
1009   /// Construct a new assembler instance.
1010   ///
1011   /// \param OS The stream to output to.
1012   //
1013   // FIXME: How are we going to parameterize this? Two obvious options are stay
1014   // concrete and require clients to pass in a target like object. The other
1015   // option is to make this abstract, and have targets provide concrete
1016   // implementations as we do with AsmParser.
1017   MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
1018               MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
1019               raw_ostream &OS);
1020   ~MCAssembler();
1021
1022   /// Reuse an assembler instance
1023   ///
1024   void reset();
1025
1026   MCContext &getContext() const { return Context; }
1027
1028   MCAsmBackend &getBackend() const { return Backend; }
1029
1030   MCCodeEmitter &getEmitter() const { return Emitter; }
1031
1032   MCObjectWriter &getWriter() const { return Writer; }
1033
1034   /// Finish - Do final processing and write the object to the output stream.
1035   /// \p Writer is used for custom object writer (as the MCJIT does),
1036   /// if not specified it is automatically created from backend.
1037   void Finish();
1038
1039   // FIXME: This does not belong here.
1040   bool getSubsectionsViaSymbols() const {
1041     return SubsectionsViaSymbols;
1042   }
1043   void setSubsectionsViaSymbols(bool Value) {
1044     SubsectionsViaSymbols = Value;
1045   }
1046
1047   bool getRelaxAll() const { return RelaxAll; }
1048   void setRelaxAll(bool Value) { RelaxAll = Value; }
1049
1050   bool getNoExecStack() const { return NoExecStack; }
1051   void setNoExecStack(bool Value) { NoExecStack = Value; }
1052
1053   bool isBundlingEnabled() const {
1054     return BundleAlignSize != 0;
1055   }
1056
1057   unsigned getBundleAlignSize() const {
1058     return BundleAlignSize;
1059   }
1060
1061   void setBundleAlignSize(unsigned Size) {
1062     assert((Size == 0 || !(Size & (Size - 1))) && 
1063            "Expect a power-of-two bundle align size");
1064     BundleAlignSize = Size;
1065   }
1066
1067   /// @name Section List Access
1068   /// @{
1069
1070   const SectionDataListType &getSectionList() const { return Sections; }
1071   SectionDataListType &getSectionList() { return Sections; }
1072
1073   iterator begin() { return Sections.begin(); }
1074   const_iterator begin() const { return Sections.begin(); }
1075
1076   iterator end() { return Sections.end(); }
1077   const_iterator end() const { return Sections.end(); }
1078
1079   size_t size() const { return Sections.size(); }
1080
1081   /// @}
1082   /// @name Symbol List Access
1083   /// @{
1084
1085   const SymbolDataListType &getSymbolList() const { return Symbols; }
1086   SymbolDataListType &getSymbolList() { return Symbols; }
1087
1088   symbol_iterator symbol_begin() { return Symbols.begin(); }
1089   const_symbol_iterator symbol_begin() const { return Symbols.begin(); }
1090
1091   symbol_iterator symbol_end() { return Symbols.end(); }
1092   const_symbol_iterator symbol_end() const { return Symbols.end(); }
1093
1094   size_t symbol_size() const { return Symbols.size(); }
1095
1096   /// @}
1097   /// @name Indirect Symbol List Access
1098   /// @{
1099
1100   // FIXME: This is a total hack, this should not be here. Once things are
1101   // factored so that the streamer has direct access to the .o writer, it can
1102   // disappear.
1103   std::vector<IndirectSymbolData> &getIndirectSymbols() {
1104     return IndirectSymbols;
1105   }
1106
1107   indirect_symbol_iterator indirect_symbol_begin() {
1108     return IndirectSymbols.begin();
1109   }
1110   const_indirect_symbol_iterator indirect_symbol_begin() const {
1111     return IndirectSymbols.begin();
1112   }
1113
1114   indirect_symbol_iterator indirect_symbol_end() {
1115     return IndirectSymbols.end();
1116   }
1117   const_indirect_symbol_iterator indirect_symbol_end() const {
1118     return IndirectSymbols.end();
1119   }
1120
1121   size_t indirect_symbol_size() const { return IndirectSymbols.size(); }
1122
1123   /// @}
1124   /// @name Linker Option List Access
1125   /// @{
1126
1127   std::vector<std::vector<std::string> > &getLinkerOptions() {
1128     return LinkerOptions;
1129   }
1130
1131   /// @}
1132   /// @name Data Region List Access
1133   /// @{
1134
1135   // FIXME: This is a total hack, this should not be here. Once things are
1136   // factored so that the streamer has direct access to the .o writer, it can
1137   // disappear.
1138   std::vector<DataRegionData> &getDataRegions() {
1139     return DataRegions;
1140   }
1141
1142   data_region_iterator data_region_begin() {
1143     return DataRegions.begin();
1144   }
1145   const_data_region_iterator data_region_begin() const {
1146     return DataRegions.begin();
1147   }
1148
1149   data_region_iterator data_region_end() {
1150     return DataRegions.end();
1151   }
1152   const_data_region_iterator data_region_end() const {
1153     return DataRegions.end();
1154   }
1155
1156   size_t data_region_size() const { return DataRegions.size(); }
1157
1158   /// @}
1159   /// @name Backend Data Access
1160   /// @{
1161
1162   MCSectionData &getSectionData(const MCSection &Section) const {
1163     MCSectionData *Entry = SectionMap.lookup(&Section);
1164     assert(Entry && "Missing section data!");
1165     return *Entry;
1166   }
1167
1168   MCSectionData &getOrCreateSectionData(const MCSection &Section,
1169                                         bool *Created = 0) {
1170     MCSectionData *&Entry = SectionMap[&Section];
1171
1172     if (Created) *Created = !Entry;
1173     if (!Entry)
1174       Entry = new MCSectionData(Section, this);
1175
1176     return *Entry;
1177   }
1178
1179   bool hasSymbolData(const MCSymbol &Symbol) const {
1180     return SymbolMap.lookup(&Symbol) != 0;
1181   }
1182
1183   MCSymbolData &getSymbolData(const MCSymbol &Symbol) const {
1184     MCSymbolData *Entry = SymbolMap.lookup(&Symbol);
1185     assert(Entry && "Missing symbol data!");
1186     return *Entry;
1187   }
1188
1189   MCSymbolData &getOrCreateSymbolData(const MCSymbol &Symbol,
1190                                       bool *Created = 0) {
1191     MCSymbolData *&Entry = SymbolMap[&Symbol];
1192
1193     if (Created) *Created = !Entry;
1194     if (!Entry)
1195       Entry = new MCSymbolData(Symbol, 0, 0, this);
1196
1197     return *Entry;
1198   }
1199
1200   const_file_name_iterator file_names_begin() const {
1201     return FileNames.begin();
1202   }
1203
1204   const_file_name_iterator file_names_end() const {
1205     return FileNames.end();
1206   }
1207
1208   void addFileName(StringRef FileName) {
1209     if (std::find(file_names_begin(), file_names_end(), FileName) ==
1210         file_names_end())
1211       FileNames.push_back(FileName);
1212   }
1213
1214   /// @}
1215
1216   void dump();
1217 };
1218
1219 } // end namespace llvm
1220
1221 #endif