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