MC: make WinEH opcode an opaque value
[oota-llvm.git] / lib / MC / MCWin64EH.cpp
1 //===- lib/MC/MCWin64EH.cpp - MCWin64EH implementation --------------------===//
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 #include "llvm/MC/MCWin64EH.h"
11 #include "llvm/ADT/Twine.h"
12 #include "llvm/MC/MCContext.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCObjectFileInfo.h"
15 #include "llvm/MC/MCSectionCOFF.h"
16 #include "llvm/MC/MCStreamer.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/Support/Win64EH.h"
19
20 namespace llvm {
21
22 // NOTE: All relocations generated here are 4-byte image-relative.
23
24 static uint8_t CountOfUnwindCodes(std::vector<WinEH::Instruction> &Insns) {
25   uint8_t Count = 0;
26   for (const auto &I : Insns) {
27     switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) {
28     case Win64EH::UOP_PushNonVol:
29     case Win64EH::UOP_AllocSmall:
30     case Win64EH::UOP_SetFPReg:
31     case Win64EH::UOP_PushMachFrame:
32       Count += 1;
33       break;
34     case Win64EH::UOP_SaveNonVol:
35     case Win64EH::UOP_SaveXMM128:
36       Count += 2;
37       break;
38     case Win64EH::UOP_SaveNonVolBig:
39     case Win64EH::UOP_SaveXMM128Big:
40       Count += 3;
41       break;
42     case Win64EH::UOP_AllocLarge:
43       Count += (I.Offset > 512 * 1024 - 8) ? 3 : 2;
44       break;
45     }
46   }
47   return Count;
48 }
49
50 static void EmitAbsDifference(MCStreamer &Streamer, const MCSymbol *LHS,
51                               const MCSymbol *RHS) {
52   MCContext &Context = Streamer.getContext();
53   const MCExpr *Diff =
54       MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(LHS, Context),
55                               MCSymbolRefExpr::Create(RHS, Context), Context);
56   Streamer.EmitAbsValue(Diff, 1);
57 }
58
59 static void EmitUnwindCode(MCStreamer &streamer, MCSymbol *begin,
60                            WinEH::Instruction &inst) {
61   uint8_t b2;
62   uint16_t w;
63   b2 = (inst.Operation & 0x0F);
64   switch (static_cast<Win64EH::UnwindOpcodes>(inst.Operation)) {
65   case Win64EH::UOP_PushNonVol:
66     EmitAbsDifference(streamer, inst.Label, begin);
67     b2 |= (inst.Register & 0x0F) << 4;
68     streamer.EmitIntValue(b2, 1);
69     break;
70   case Win64EH::UOP_AllocLarge:
71     EmitAbsDifference(streamer, inst.Label, begin);
72     if (inst.Offset > 512 * 1024 - 8) {
73       b2 |= 0x10;
74       streamer.EmitIntValue(b2, 1);
75       w = inst.Offset & 0xFFF8;
76       streamer.EmitIntValue(w, 2);
77       w = inst.Offset >> 16;
78     } else {
79       streamer.EmitIntValue(b2, 1);
80       w = inst.Offset >> 3;
81     }
82     streamer.EmitIntValue(w, 2);
83     break;
84   case Win64EH::UOP_AllocSmall:
85     b2 |= (((inst.Offset - 8) >> 3) & 0x0F) << 4;
86     EmitAbsDifference(streamer, inst.Label, begin);
87     streamer.EmitIntValue(b2, 1);
88     break;
89   case Win64EH::UOP_SetFPReg:
90     EmitAbsDifference(streamer, inst.Label, begin);
91     streamer.EmitIntValue(b2, 1);
92     break;
93   case Win64EH::UOP_SaveNonVol:
94   case Win64EH::UOP_SaveXMM128:
95     b2 |= (inst.Register & 0x0F) << 4;
96     EmitAbsDifference(streamer, inst.Label, begin);
97     streamer.EmitIntValue(b2, 1);
98     w = inst.Offset >> 3;
99     if (inst.Operation == Win64EH::UOP_SaveXMM128)
100       w >>= 1;
101     streamer.EmitIntValue(w, 2);
102     break;
103   case Win64EH::UOP_SaveNonVolBig:
104   case Win64EH::UOP_SaveXMM128Big:
105     b2 |= (inst.Register & 0x0F) << 4;
106     EmitAbsDifference(streamer, inst.Label, begin);
107     streamer.EmitIntValue(b2, 1);
108     if (inst.Operation == Win64EH::UOP_SaveXMM128Big)
109       w = inst.Offset & 0xFFF0;
110     else
111       w = inst.Offset & 0xFFF8;
112     streamer.EmitIntValue(w, 2);
113     w = inst.Offset >> 16;
114     streamer.EmitIntValue(w, 2);
115     break;
116   case Win64EH::UOP_PushMachFrame:
117     if (inst.Offset == 1)
118       b2 |= 0x10;
119     EmitAbsDifference(streamer, inst.Label, begin);
120     streamer.EmitIntValue(b2, 1);
121     break;
122   }
123 }
124
125 static void EmitSymbolRefWithOfs(MCStreamer &streamer,
126                                  const MCSymbol *Base,
127                                  const MCSymbol *Other) {
128   MCContext &Context = streamer.getContext();
129   const MCSymbolRefExpr *BaseRef = MCSymbolRefExpr::Create(Base, Context);
130   const MCSymbolRefExpr *OtherRef = MCSymbolRefExpr::Create(Other, Context);
131   const MCExpr *Ofs = MCBinaryExpr::CreateSub(OtherRef, BaseRef, Context);
132   const MCSymbolRefExpr *BaseRefRel = MCSymbolRefExpr::Create(Base,
133                                               MCSymbolRefExpr::VK_COFF_IMGREL32,
134                                               Context);
135   streamer.EmitValue(MCBinaryExpr::CreateAdd(BaseRefRel, Ofs, Context), 4);
136 }
137
138 static void EmitRuntimeFunction(MCStreamer &streamer,
139                                 const MCWinFrameInfo *info) {
140   MCContext &context = streamer.getContext();
141
142   streamer.EmitValueToAlignment(4);
143   EmitSymbolRefWithOfs(streamer, info->Function, info->Begin);
144   EmitSymbolRefWithOfs(streamer, info->Function, info->End);
145   streamer.EmitValue(MCSymbolRefExpr::Create(info->Symbol,
146                                              MCSymbolRefExpr::VK_COFF_IMGREL32,
147                                              context), 4);
148 }
149
150 static void EmitUnwindInfo(MCStreamer &streamer, MCWinFrameInfo *info) {
151   // If this UNWIND_INFO already has a symbol, it's already been emitted.
152   if (info->Symbol) return;
153
154   MCContext &context = streamer.getContext();
155   streamer.EmitValueToAlignment(4);
156   info->Symbol = context.CreateTempSymbol();
157   streamer.EmitLabel(info->Symbol);
158
159   // Upper 3 bits are the version number (currently 1).
160   uint8_t flags = 0x01;
161   if (info->ChainedParent)
162     flags |= Win64EH::UNW_ChainInfo << 3;
163   else {
164     if (info->HandlesUnwind)
165       flags |= Win64EH::UNW_TerminateHandler << 3;
166     if (info->HandlesExceptions)
167       flags |= Win64EH::UNW_ExceptionHandler << 3;
168   }
169   streamer.EmitIntValue(flags, 1);
170
171   if (info->PrologEnd)
172     EmitAbsDifference(streamer, info->PrologEnd, info->Begin);
173   else
174     streamer.EmitIntValue(0, 1);
175
176   uint8_t numCodes = CountOfUnwindCodes(info->Instructions);
177   streamer.EmitIntValue(numCodes, 1);
178
179   uint8_t frame = 0;
180   if (info->LastFrameInst >= 0) {
181     WinEH::Instruction &frameInst = info->Instructions[info->LastFrameInst];
182     assert(frameInst.Operation == Win64EH::UOP_SetFPReg);
183     frame = (frameInst.Register & 0x0F) | (frameInst.Offset & 0xF0);
184   }
185   streamer.EmitIntValue(frame, 1);
186
187   // Emit unwind instructions (in reverse order).
188   uint8_t numInst = info->Instructions.size();
189   for (uint8_t c = 0; c < numInst; ++c) {
190     WinEH::Instruction inst = info->Instructions.back();
191     info->Instructions.pop_back();
192     EmitUnwindCode(streamer, info->Begin, inst);
193   }
194
195   // For alignment purposes, the instruction array will always have an even
196   // number of entries, with the final entry potentially unused (in which case
197   // the array will be one longer than indicated by the count of unwind codes
198   // field).
199   if (numCodes & 1) {
200     streamer.EmitIntValue(0, 2);
201   }
202
203   if (flags & (Win64EH::UNW_ChainInfo << 3))
204     EmitRuntimeFunction(streamer, info->ChainedParent);
205   else if (flags &
206            ((Win64EH::UNW_TerminateHandler|Win64EH::UNW_ExceptionHandler) << 3))
207     streamer.EmitValue(MCSymbolRefExpr::Create(info->ExceptionHandler,
208                                               MCSymbolRefExpr::VK_COFF_IMGREL32,
209                                               context), 4);
210   else if (numCodes == 0) {
211     // The minimum size of an UNWIND_INFO struct is 8 bytes. If we're not
212     // a chained unwind info, if there is no handler, and if there are fewer
213     // than 2 slots used in the unwind code array, we have to pad to 8 bytes.
214     streamer.EmitIntValue(0, 4);
215   }
216 }
217
218 StringRef MCWin64EHUnwindEmitter::GetSectionSuffix(const MCSymbol *func) {
219   if (!func || !func->isInSection()) return "";
220   const MCSection *section = &func->getSection();
221   const MCSectionCOFF *COFFSection;
222   if ((COFFSection = dyn_cast<MCSectionCOFF>(section))) {
223     StringRef name = COFFSection->getSectionName();
224     size_t dollar = name.find('$');
225     size_t dot = name.find('.', 1);
226     if (dollar == StringRef::npos && dot == StringRef::npos)
227       return "";
228     if (dot == StringRef::npos)
229       return name.substr(dollar);
230     if (dollar == StringRef::npos || dot < dollar)
231       return name.substr(dot);
232     return name.substr(dollar);
233   }
234   return "";
235 }
236
237 static const MCSection *getWin64EHTableSection(StringRef suffix,
238                                                MCContext &context) {
239   if (suffix == "")
240     return context.getObjectFileInfo()->getXDataSection();
241
242   return context.getCOFFSection((".xdata"+suffix).str(),
243                                 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
244                                 COFF::IMAGE_SCN_MEM_READ,
245                                 SectionKind::getDataRel());
246 }
247
248 static const MCSection *getWin64EHFuncTableSection(StringRef suffix,
249                                                    MCContext &context) {
250   if (suffix == "")
251     return context.getObjectFileInfo()->getPDataSection();
252   return context.getCOFFSection((".pdata"+suffix).str(),
253                                 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
254                                 COFF::IMAGE_SCN_MEM_READ,
255                                 SectionKind::getDataRel());
256 }
257
258 void MCWin64EHUnwindEmitter::EmitUnwindInfo(MCStreamer &streamer,
259                                             MCWinFrameInfo *info) {
260   // Switch sections (the static function above is meant to be called from
261   // here and from Emit().
262   MCContext &context = streamer.getContext();
263   const MCSection *xdataSect =
264     getWin64EHTableSection(GetSectionSuffix(info->Function), context);
265   streamer.SwitchSection(xdataSect);
266
267   llvm::EmitUnwindInfo(streamer, info);
268 }
269
270 void MCWin64EHUnwindEmitter::Emit(MCStreamer &Streamer) {
271   MCContext &Context = Streamer.getContext();
272
273   // Emit the unwind info structs first.
274   for (const auto &CFI : Streamer.getWinFrameInfos()) {
275     const MCSection *XData =
276         getWin64EHTableSection(GetSectionSuffix(CFI->Function), Context);
277     Streamer.SwitchSection(XData);
278     EmitUnwindInfo(Streamer, CFI);
279   }
280
281   // Now emit RUNTIME_FUNCTION entries.
282   for (const auto &CFI : Streamer.getWinFrameInfos()) {
283     const MCSection *PData =
284         getWin64EHFuncTableSection(GetSectionSuffix(CFI->Function), Context);
285     Streamer.SwitchSection(PData);
286     EmitRuntimeFunction(Streamer, CFI);
287   }
288 }
289
290 } // End of namespace llvm
291