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