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