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