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