1 //===-- ARMAsmPrinter.cpp - Print machine code to an ARM .s file ----------===//
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 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format ARM assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ARMAsmPrinter.h"
16 #include "ARM.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMTargetMachine.h"
20 #include "ARMTargetObjectFile.h"
21 #include "InstPrinter/ARMInstPrinter.h"
22 #include "MCTargetDesc/ARMAddressingModes.h"
23 #include "MCTargetDesc/ARMMCExpr.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/Mangler.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCAssembler.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCELFStreamer.h"
39 #include "llvm/MC/MCInst.h"
40 #include "llvm/MC/MCInstBuilder.h"
41 #include "llvm/MC/MCObjectStreamer.h"
42 #include "llvm/MC/MCSectionMachO.h"
43 #include "llvm/MC/MCStreamer.h"
44 #include "llvm/MC/MCSymbol.h"
45 #include "llvm/Support/ARMBuildAttributes.h"
46 #include "llvm/Support/COFF.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ELF.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/TargetParser.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include <cctype>
55 using namespace llvm;
56 
57 #define DEBUG_TYPE "asm-printer"
58 
59 ARMAsmPrinter::ARMAsmPrinter(TargetMachine &TM,
60                              std::unique_ptr<MCStreamer> Streamer)
61     : AsmPrinter(TM, std::move(Streamer)), AFI(nullptr), MCP(nullptr),
62       InConstantPool(false), OptimizationGoals(-1) {}
63 
64 void ARMAsmPrinter::EmitFunctionBodyEnd() {
65   // Make sure to terminate any constant pools that were at the end
66   // of the function.
67   if (!InConstantPool)
68     return;
69   InConstantPool = false;
70   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
71 }
72 
73 void ARMAsmPrinter::EmitFunctionEntryLabel() {
74   if (AFI->isThumbFunction()) {
75     OutStreamer->EmitAssemblerFlag(MCAF_Code16);
76     OutStreamer->EmitThumbFunc(CurrentFnSym);
77   }
78 
79   OutStreamer->EmitLabel(CurrentFnSym);
80 }
81 
82 void ARMAsmPrinter::EmitXXStructor(const DataLayout &DL, const Constant *CV) {
83   uint64_t Size = getDataLayout().getTypeAllocSize(CV->getType());
84   assert(Size && "C++ constructor pointer had zero size!");
85 
86   const GlobalValue *GV = dyn_cast<GlobalValue>(CV->stripPointerCasts());
87   assert(GV && "C++ constructor pointer was not a GlobalValue!");
88 
89   const MCExpr *E = MCSymbolRefExpr::create(GetARMGVSymbol(GV,
90                                                            ARMII::MO_NO_FLAG),
91                                             (Subtarget->isTargetELF()
92                                              ? MCSymbolRefExpr::VK_ARM_TARGET1
93                                              : MCSymbolRefExpr::VK_None),
94                                             OutContext);
95 
96   OutStreamer->EmitValue(E, Size);
97 }
98 
99 /// runOnMachineFunction - This uses the EmitInstruction()
100 /// method to print assembly for each instruction.
101 ///
102 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
103   AFI = MF.getInfo<ARMFunctionInfo>();
104   MCP = MF.getConstantPool();
105   Subtarget = &MF.getSubtarget<ARMSubtarget>();
106 
107   SetupMachineFunction(MF);
108   const Function* F = MF.getFunction();
109   const TargetMachine& TM = MF.getTarget();
110 
111   // Calculate this function's optimization goal.
112   unsigned OptimizationGoal;
113   if (F->hasFnAttribute(Attribute::OptimizeNone))
114     // For best debugging illusion, speed and small size sacrificed
115     OptimizationGoal = 6;
116   else if (F->optForMinSize())
117     // Aggressively for small size, speed and debug illusion sacrificed
118     OptimizationGoal = 4;
119   else if (F->optForSize())
120     // For small size, but speed and debugging illusion preserved
121     OptimizationGoal = 3;
122   else if (TM.getOptLevel() == CodeGenOpt::Aggressive)
123     // Aggressively for speed, small size and debug illusion sacrificed
124     OptimizationGoal = 2;
125   else if (TM.getOptLevel() > CodeGenOpt::None)
126     // For speed, but small size and good debug illusion preserved
127     OptimizationGoal = 1;
128   else // TM.getOptLevel() == CodeGenOpt::None
129     // For good debugging, but speed and small size preserved
130     OptimizationGoal = 5;
131 
132   // Combine a new optimization goal with existing ones.
133   if (OptimizationGoals == -1) // uninitialized goals
134     OptimizationGoals = OptimizationGoal;
135   else if (OptimizationGoals != (int)OptimizationGoal) // conflicting goals
136     OptimizationGoals = 0;
137 
138   if (Subtarget->isTargetCOFF()) {
139     bool Internal = F->hasInternalLinkage();
140     COFF::SymbolStorageClass Scl = Internal ? COFF::IMAGE_SYM_CLASS_STATIC
141                                             : COFF::IMAGE_SYM_CLASS_EXTERNAL;
142     int Type = COFF::IMAGE_SYM_DTYPE_FUNCTION << COFF::SCT_COMPLEX_TYPE_SHIFT;
143 
144     OutStreamer->BeginCOFFSymbolDef(CurrentFnSym);
145     OutStreamer->EmitCOFFSymbolStorageClass(Scl);
146     OutStreamer->EmitCOFFSymbolType(Type);
147     OutStreamer->EndCOFFSymbolDef();
148   }
149 
150   // Emit the rest of the function body.
151   EmitFunctionBody();
152 
153   // If we need V4T thumb mode Register Indirect Jump pads, emit them.
154   // These are created per function, rather than per TU, since it's
155   // relatively easy to exceed the thumb branch range within a TU.
156   if (! ThumbIndirectPads.empty()) {
157     OutStreamer->EmitAssemblerFlag(MCAF_Code16);
158     EmitAlignment(1);
159     for (unsigned i = 0, e = ThumbIndirectPads.size(); i < e; i++) {
160       OutStreamer->EmitLabel(ThumbIndirectPads[i].second);
161       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
162         .addReg(ThumbIndirectPads[i].first)
163         // Add predicate operands.
164         .addImm(ARMCC::AL)
165         .addReg(0));
166     }
167     ThumbIndirectPads.clear();
168   }
169 
170   // We didn't modify anything.
171   return false;
172 }
173 
174 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
175                                  raw_ostream &O) {
176   const MachineOperand &MO = MI->getOperand(OpNum);
177   unsigned TF = MO.getTargetFlags();
178 
179   switch (MO.getType()) {
180   default: llvm_unreachable("<unknown operand type>");
181   case MachineOperand::MO_Register: {
182     unsigned Reg = MO.getReg();
183     assert(TargetRegisterInfo::isPhysicalRegister(Reg));
184     assert(!MO.getSubReg() && "Subregs should be eliminated!");
185     if(ARM::GPRPairRegClass.contains(Reg)) {
186       const MachineFunction &MF = *MI->getParent()->getParent();
187       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
188       Reg = TRI->getSubReg(Reg, ARM::gsub_0);
189     }
190     O << ARMInstPrinter::getRegisterName(Reg);
191     break;
192   }
193   case MachineOperand::MO_Immediate: {
194     int64_t Imm = MO.getImm();
195     O << '#';
196     if (TF == ARMII::MO_LO16)
197       O << ":lower16:";
198     else if (TF == ARMII::MO_HI16)
199       O << ":upper16:";
200     O << Imm;
201     break;
202   }
203   case MachineOperand::MO_MachineBasicBlock:
204     MO.getMBB()->getSymbol()->print(O, MAI);
205     return;
206   case MachineOperand::MO_GlobalAddress: {
207     const GlobalValue *GV = MO.getGlobal();
208     if (TF & ARMII::MO_LO16)
209       O << ":lower16:";
210     else if (TF & ARMII::MO_HI16)
211       O << ":upper16:";
212     GetARMGVSymbol(GV, TF)->print(O, MAI);
213 
214     printOffset(MO.getOffset(), O);
215     break;
216   }
217   case MachineOperand::MO_ConstantPoolIndex:
218     GetCPISymbol(MO.getIndex())->print(O, MAI);
219     break;
220   }
221 }
222 
223 //===--------------------------------------------------------------------===//
224 
225 MCSymbol *ARMAsmPrinter::
226 GetARMJTIPICJumpTableLabel(unsigned uid) const {
227   const DataLayout &DL = getDataLayout();
228   SmallString<60> Name;
229   raw_svector_ostream(Name) << DL.getPrivateGlobalPrefix() << "JTI"
230                             << getFunctionNumber() << '_' << uid;
231   return OutContext.getOrCreateSymbol(Name);
232 }
233 
234 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
235                                     unsigned AsmVariant, const char *ExtraCode,
236                                     raw_ostream &O) {
237   // Does this asm operand have a single letter operand modifier?
238   if (ExtraCode && ExtraCode[0]) {
239     if (ExtraCode[1] != 0) return true; // Unknown modifier.
240 
241     switch (ExtraCode[0]) {
242     default:
243       // See if this is a generic print operand
244       return AsmPrinter::PrintAsmOperand(MI, OpNum, AsmVariant, ExtraCode, O);
245     case 'a': // Print as a memory address.
246       if (MI->getOperand(OpNum).isReg()) {
247         O << "["
248           << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg())
249           << "]";
250         return false;
251       }
252       // Fallthrough
253     case 'c': // Don't print "#" before an immediate operand.
254       if (!MI->getOperand(OpNum).isImm())
255         return true;
256       O << MI->getOperand(OpNum).getImm();
257       return false;
258     case 'P': // Print a VFP double precision register.
259     case 'q': // Print a NEON quad precision register.
260       printOperand(MI, OpNum, O);
261       return false;
262     case 'y': // Print a VFP single precision register as indexed double.
263       if (MI->getOperand(OpNum).isReg()) {
264         unsigned Reg = MI->getOperand(OpNum).getReg();
265         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
266         // Find the 'd' register that has this 's' register as a sub-register,
267         // and determine the lane number.
268         for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
269           if (!ARM::DPRRegClass.contains(*SR))
270             continue;
271           bool Lane0 = TRI->getSubReg(*SR, ARM::ssub_0) == Reg;
272           O << ARMInstPrinter::getRegisterName(*SR) << (Lane0 ? "[0]" : "[1]");
273           return false;
274         }
275       }
276       return true;
277     case 'B': // Bitwise inverse of integer or symbol without a preceding #.
278       if (!MI->getOperand(OpNum).isImm())
279         return true;
280       O << ~(MI->getOperand(OpNum).getImm());
281       return false;
282     case 'L': // The low 16 bits of an immediate constant.
283       if (!MI->getOperand(OpNum).isImm())
284         return true;
285       O << (MI->getOperand(OpNum).getImm() & 0xffff);
286       return false;
287     case 'M': { // A register range suitable for LDM/STM.
288       if (!MI->getOperand(OpNum).isReg())
289         return true;
290       const MachineOperand &MO = MI->getOperand(OpNum);
291       unsigned RegBegin = MO.getReg();
292       // This takes advantage of the 2 operand-ness of ldm/stm and that we've
293       // already got the operands in registers that are operands to the
294       // inline asm statement.
295       O << "{";
296       if (ARM::GPRPairRegClass.contains(RegBegin)) {
297         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
298         unsigned Reg0 = TRI->getSubReg(RegBegin, ARM::gsub_0);
299         O << ARMInstPrinter::getRegisterName(Reg0) << ", ";
300         RegBegin = TRI->getSubReg(RegBegin, ARM::gsub_1);
301       }
302       O << ARMInstPrinter::getRegisterName(RegBegin);
303 
304       // FIXME: The register allocator not only may not have given us the
305       // registers in sequence, but may not be in ascending registers. This
306       // will require changes in the register allocator that'll need to be
307       // propagated down here if the operands change.
308       unsigned RegOps = OpNum + 1;
309       while (MI->getOperand(RegOps).isReg()) {
310         O << ", "
311           << ARMInstPrinter::getRegisterName(MI->getOperand(RegOps).getReg());
312         RegOps++;
313       }
314 
315       O << "}";
316 
317       return false;
318     }
319     case 'R': // The most significant register of a pair.
320     case 'Q': { // The least significant register of a pair.
321       if (OpNum == 0)
322         return true;
323       const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
324       if (!FlagsOP.isImm())
325         return true;
326       unsigned Flags = FlagsOP.getImm();
327 
328       // This operand may not be the one that actually provides the register. If
329       // it's tied to a previous one then we should refer instead to that one
330       // for registers and their classes.
331       unsigned TiedIdx;
332       if (InlineAsm::isUseOperandTiedToDef(Flags, TiedIdx)) {
333         for (OpNum = InlineAsm::MIOp_FirstOperand; TiedIdx; --TiedIdx) {
334           unsigned OpFlags = MI->getOperand(OpNum).getImm();
335           OpNum += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
336         }
337         Flags = MI->getOperand(OpNum).getImm();
338 
339         // Later code expects OpNum to be pointing at the register rather than
340         // the flags.
341         OpNum += 1;
342       }
343 
344       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
345       unsigned RC;
346       InlineAsm::hasRegClassConstraint(Flags, RC);
347       if (RC == ARM::GPRPairRegClassID) {
348         if (NumVals != 1)
349           return true;
350         const MachineOperand &MO = MI->getOperand(OpNum);
351         if (!MO.isReg())
352           return true;
353         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
354         unsigned Reg = TRI->getSubReg(MO.getReg(), ExtraCode[0] == 'Q' ?
355             ARM::gsub_0 : ARM::gsub_1);
356         O << ARMInstPrinter::getRegisterName(Reg);
357         return false;
358       }
359       if (NumVals != 2)
360         return true;
361       unsigned RegOp = ExtraCode[0] == 'Q' ? OpNum : OpNum + 1;
362       if (RegOp >= MI->getNumOperands())
363         return true;
364       const MachineOperand &MO = MI->getOperand(RegOp);
365       if (!MO.isReg())
366         return true;
367       unsigned Reg = MO.getReg();
368       O << ARMInstPrinter::getRegisterName(Reg);
369       return false;
370     }
371 
372     case 'e': // The low doubleword register of a NEON quad register.
373     case 'f': { // The high doubleword register of a NEON quad register.
374       if (!MI->getOperand(OpNum).isReg())
375         return true;
376       unsigned Reg = MI->getOperand(OpNum).getReg();
377       if (!ARM::QPRRegClass.contains(Reg))
378         return true;
379       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
380       unsigned SubReg = TRI->getSubReg(Reg, ExtraCode[0] == 'e' ?
381                                        ARM::dsub_0 : ARM::dsub_1);
382       O << ARMInstPrinter::getRegisterName(SubReg);
383       return false;
384     }
385 
386     // This modifier is not yet supported.
387     case 'h': // A range of VFP/NEON registers suitable for VLD1/VST1.
388       return true;
389     case 'H': { // The highest-numbered register of a pair.
390       const MachineOperand &MO = MI->getOperand(OpNum);
391       if (!MO.isReg())
392         return true;
393       const MachineFunction &MF = *MI->getParent()->getParent();
394       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
395       unsigned Reg = MO.getReg();
396       if(!ARM::GPRPairRegClass.contains(Reg))
397         return false;
398       Reg = TRI->getSubReg(Reg, ARM::gsub_1);
399       O << ARMInstPrinter::getRegisterName(Reg);
400       return false;
401     }
402     }
403   }
404 
405   printOperand(MI, OpNum, O);
406   return false;
407 }
408 
409 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
410                                           unsigned OpNum, unsigned AsmVariant,
411                                           const char *ExtraCode,
412                                           raw_ostream &O) {
413   // Does this asm operand have a single letter operand modifier?
414   if (ExtraCode && ExtraCode[0]) {
415     if (ExtraCode[1] != 0) return true; // Unknown modifier.
416 
417     switch (ExtraCode[0]) {
418       case 'A': // A memory operand for a VLD1/VST1 instruction.
419       default: return true;  // Unknown modifier.
420       case 'm': // The base register of a memory operand.
421         if (!MI->getOperand(OpNum).isReg())
422           return true;
423         O << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg());
424         return false;
425     }
426   }
427 
428   const MachineOperand &MO = MI->getOperand(OpNum);
429   assert(MO.isReg() && "unexpected inline asm memory operand");
430   O << "[" << ARMInstPrinter::getRegisterName(MO.getReg()) << "]";
431   return false;
432 }
433 
434 static bool isThumb(const MCSubtargetInfo& STI) {
435   return STI.getFeatureBits()[ARM::ModeThumb];
436 }
437 
438 void ARMAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
439                                      const MCSubtargetInfo *EndInfo) const {
440   // If either end mode is unknown (EndInfo == NULL) or different than
441   // the start mode, then restore the start mode.
442   const bool WasThumb = isThumb(StartInfo);
443   if (!EndInfo || WasThumb != isThumb(*EndInfo)) {
444     OutStreamer->EmitAssemblerFlag(WasThumb ? MCAF_Code16 : MCAF_Code32);
445   }
446 }
447 
448 void ARMAsmPrinter::EmitStartOfAsmFile(Module &M) {
449   const Triple &TT = TM.getTargetTriple();
450   // Use unified assembler syntax.
451   OutStreamer->EmitAssemblerFlag(MCAF_SyntaxUnified);
452 
453   // Emit ARM Build Attributes
454   if (TT.isOSBinFormatELF())
455     emitAttributes();
456 
457   // Use the triple's architecture and subarchitecture to determine
458   // if we're thumb for the purposes of the top level code16 assembler
459   // flag.
460   bool isThumb = TT.getArch() == Triple::thumb ||
461                  TT.getArch() == Triple::thumbeb ||
462                  TT.getSubArch() == Triple::ARMSubArch_v7m ||
463                  TT.getSubArch() == Triple::ARMSubArch_v6m;
464   if (!M.getModuleInlineAsm().empty() && isThumb)
465     OutStreamer->EmitAssemblerFlag(MCAF_Code16);
466 }
467 
468 static void
469 emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
470                          MachineModuleInfoImpl::StubValueTy &MCSym) {
471   // L_foo$stub:
472   OutStreamer.EmitLabel(StubLabel);
473   //   .indirect_symbol _foo
474   OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
475 
476   if (MCSym.getInt())
477     // External to current translation unit.
478     OutStreamer.EmitIntValue(0, 4/*size*/);
479   else
480     // Internal to current translation unit.
481     //
482     // When we place the LSDA into the TEXT section, the type info
483     // pointers need to be indirect and pc-rel. We accomplish this by
484     // using NLPs; however, sometimes the types are local to the file.
485     // We need to fill in the value for the NLP in those cases.
486     OutStreamer.EmitValue(
487         MCSymbolRefExpr::create(MCSym.getPointer(), OutStreamer.getContext()),
488         4 /*size*/);
489 }
490 
491 
492 void ARMAsmPrinter::EmitEndOfAsmFile(Module &M) {
493   const Triple &TT = TM.getTargetTriple();
494   if (TT.isOSBinFormatMachO()) {
495     // All darwin targets use mach-o.
496     const TargetLoweringObjectFileMachO &TLOFMacho =
497       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
498     MachineModuleInfoMachO &MMIMacho =
499       MMI->getObjFileInfo<MachineModuleInfoMachO>();
500 
501     // Output non-lazy-pointers for external and common global variables.
502     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
503 
504     if (!Stubs.empty()) {
505       // Switch with ".non_lazy_symbol_pointer" directive.
506       OutStreamer->SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
507       EmitAlignment(2);
508 
509       for (auto &Stub : Stubs)
510         emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
511 
512       Stubs.clear();
513       OutStreamer->AddBlankLine();
514     }
515 
516     Stubs = MMIMacho.GetThreadLocalGVStubList();
517     if (!Stubs.empty()) {
518       // Switch with ".non_lazy_symbol_pointer" directive.
519       OutStreamer->SwitchSection(TLOFMacho.getThreadLocalPointerSection());
520       EmitAlignment(2);
521 
522       for (auto &Stub : Stubs)
523         emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
524 
525       Stubs.clear();
526       OutStreamer->AddBlankLine();
527     }
528 
529     // Funny Darwin hack: This flag tells the linker that no global symbols
530     // contain code that falls through to other global symbols (e.g. the obvious
531     // implementation of multiple entry points).  If this doesn't occur, the
532     // linker can safely perform dead code stripping.  Since LLVM never
533     // generates code that does this, it is always safe to set.
534     OutStreamer->EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
535   }
536 
537   if (TT.isOSBinFormatCOFF()) {
538     const auto &TLOF =
539         static_cast<const TargetLoweringObjectFileCOFF &>(getObjFileLowering());
540 
541     std::string Flags;
542     raw_string_ostream OS(Flags);
543 
544     for (const auto &Function : M)
545       TLOF.emitLinkerFlagsForGlobal(OS, &Function, *Mang);
546     for (const auto &Global : M.globals())
547       TLOF.emitLinkerFlagsForGlobal(OS, &Global, *Mang);
548     for (const auto &Alias : M.aliases())
549       TLOF.emitLinkerFlagsForGlobal(OS, &Alias, *Mang);
550 
551     OS.flush();
552 
553     // Output collected flags
554     if (!Flags.empty()) {
555       OutStreamer->SwitchSection(TLOF.getDrectveSection());
556       OutStreamer->EmitBytes(Flags);
557     }
558   }
559 
560   // The last attribute to be emitted is ABI_optimization_goals
561   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
562   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
563 
564   if (OptimizationGoals > 0 &&
565       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI()))
566     ATS.emitAttribute(ARMBuildAttrs::ABI_optimization_goals, OptimizationGoals);
567   OptimizationGoals = -1;
568 
569   ATS.finishAttributeSection();
570 }
571 
572 static bool isV8M(const ARMSubtarget *Subtarget) {
573   // Note that v8M Baseline is a subset of v6T2!
574   return (Subtarget->hasV8MBaselineOps() && !Subtarget->hasV6T2Ops()) ||
575          Subtarget->hasV8MMainlineOps();
576 }
577 
578 //===----------------------------------------------------------------------===//
579 // Helper routines for EmitStartOfAsmFile() and EmitEndOfAsmFile()
580 // FIXME:
581 // The following seem like one-off assembler flags, but they actually need
582 // to appear in the .ARM.attributes section in ELF.
583 // Instead of subclassing the MCELFStreamer, we do the work here.
584 
585 static ARMBuildAttrs::CPUArch getArchForCPU(StringRef CPU,
586                                             const ARMSubtarget *Subtarget) {
587   if (CPU == "xscale")
588     return ARMBuildAttrs::v5TEJ;
589 
590   if (Subtarget->hasV8Ops())
591     return ARMBuildAttrs::v8_A;
592   else if (Subtarget->hasV8MMainlineOps())
593     return ARMBuildAttrs::v8_M_Main;
594   else if (Subtarget->hasV7Ops()) {
595     if (Subtarget->isMClass() && Subtarget->hasDSP())
596       return ARMBuildAttrs::v7E_M;
597     return ARMBuildAttrs::v7;
598   } else if (Subtarget->hasV6T2Ops())
599     return ARMBuildAttrs::v6T2;
600   else if (Subtarget->hasV8MBaselineOps())
601     return ARMBuildAttrs::v8_M_Base;
602   else if (Subtarget->hasV6MOps())
603     return ARMBuildAttrs::v6S_M;
604   else if (Subtarget->hasV6Ops())
605     return ARMBuildAttrs::v6;
606   else if (Subtarget->hasV5TEOps())
607     return ARMBuildAttrs::v5TE;
608   else if (Subtarget->hasV5TOps())
609     return ARMBuildAttrs::v5T;
610   else if (Subtarget->hasV4TOps())
611     return ARMBuildAttrs::v4T;
612   else
613     return ARMBuildAttrs::v4;
614 }
615 
616 bool ARMAsmPrinter::isPositionIndependent() const {
617   return TM.getRelocationModel() == Reloc::PIC_;
618 }
619 
620 void ARMAsmPrinter::emitAttributes() {
621   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
622   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
623 
624   ATS.emitTextAttribute(ARMBuildAttrs::conformance, "2.09");
625 
626   ATS.switchVendor("aeabi");
627 
628   // Compute ARM ELF Attributes based on the default subtarget that
629   // we'd have constructed. The existing ARM behavior isn't LTO clean
630   // anyhow.
631   // FIXME: For ifunc related functions we could iterate over and look
632   // for a feature string that doesn't match the default one.
633   const Triple &TT = TM.getTargetTriple();
634   StringRef CPU = TM.getTargetCPU();
635   StringRef FS = TM.getTargetFeatureString();
636   std::string ArchFS = ARM_MC::ParseARMTriple(TT, CPU);
637   if (!FS.empty()) {
638     if (!ArchFS.empty())
639       ArchFS = (Twine(ArchFS) + "," + FS).str();
640     else
641       ArchFS = FS;
642   }
643   const ARMBaseTargetMachine &ATM =
644       static_cast<const ARMBaseTargetMachine &>(TM);
645   const ARMSubtarget STI(TT, CPU, ArchFS, ATM, ATM.isLittleEndian());
646 
647   const std::string &CPUString = STI.getCPUString();
648 
649   if (!StringRef(CPUString).startswith("generic")) {
650     // FIXME: remove krait check when GNU tools support krait cpu
651     if (STI.isKrait()) {
652       ATS.emitTextAttribute(ARMBuildAttrs::CPU_name, "cortex-a9");
653       // We consider krait as a "cortex-a9" + hwdiv CPU
654       // Enable hwdiv through ".arch_extension idiv"
655       if (STI.hasDivide() || STI.hasDivideInARMMode())
656         ATS.emitArchExtension(ARM::AEK_HWDIV | ARM::AEK_HWDIVARM);
657     } else
658       ATS.emitTextAttribute(ARMBuildAttrs::CPU_name, CPUString);
659   }
660 
661   ATS.emitAttribute(ARMBuildAttrs::CPU_arch, getArchForCPU(CPUString, &STI));
662 
663   // Tag_CPU_arch_profile must have the default value of 0 when "Architecture
664   // profile is not applicable (e.g. pre v7, or cross-profile code)".
665   if (STI.hasV7Ops() || isV8M(&STI)) {
666     if (STI.isAClass()) {
667       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
668                         ARMBuildAttrs::ApplicationProfile);
669     } else if (STI.isRClass()) {
670       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
671                         ARMBuildAttrs::RealTimeProfile);
672     } else if (STI.isMClass()) {
673       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
674                         ARMBuildAttrs::MicroControllerProfile);
675     }
676   }
677 
678   ATS.emitAttribute(ARMBuildAttrs::ARM_ISA_use,
679                     STI.hasARMOps() ? ARMBuildAttrs::Allowed
680                                     : ARMBuildAttrs::Not_Allowed);
681   if (isV8M(&STI)) {
682     ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use,
683                       ARMBuildAttrs::AllowThumbDerived);
684   } else if (STI.isThumb1Only()) {
685     ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use, ARMBuildAttrs::Allowed);
686   } else if (STI.hasThumb2()) {
687     ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use,
688                       ARMBuildAttrs::AllowThumb32);
689   }
690 
691   if (STI.hasNEON()) {
692     /* NEON is not exactly a VFP architecture, but GAS emit one of
693      * neon/neon-fp-armv8/neon-vfpv4/vfpv3/vfpv2 for .fpu parameters */
694     if (STI.hasFPARMv8()) {
695       if (STI.hasCrypto())
696         ATS.emitFPU(ARM::FK_CRYPTO_NEON_FP_ARMV8);
697       else
698         ATS.emitFPU(ARM::FK_NEON_FP_ARMV8);
699     } else if (STI.hasVFP4())
700       ATS.emitFPU(ARM::FK_NEON_VFPV4);
701     else
702       ATS.emitFPU(STI.hasFP16() ? ARM::FK_NEON_FP16 : ARM::FK_NEON);
703     // Emit Tag_Advanced_SIMD_arch for ARMv8 architecture
704     if (STI.hasV8Ops())
705       ATS.emitAttribute(ARMBuildAttrs::Advanced_SIMD_arch,
706                         STI.hasV8_1aOps() ? ARMBuildAttrs::AllowNeonARMv8_1a:
707                                             ARMBuildAttrs::AllowNeonARMv8);
708   } else {
709     if (STI.hasFPARMv8())
710       // FPv5 and FP-ARMv8 have the same instructions, so are modeled as one
711       // FPU, but there are two different names for it depending on the CPU.
712       ATS.emitFPU(STI.hasD16()
713                   ? (STI.isFPOnlySP() ? ARM::FK_FPV5_SP_D16 : ARM::FK_FPV5_D16)
714                   : ARM::FK_FP_ARMV8);
715     else if (STI.hasVFP4())
716       ATS.emitFPU(STI.hasD16()
717                   ? (STI.isFPOnlySP() ? ARM::FK_FPV4_SP_D16 : ARM::FK_VFPV4_D16)
718                   : ARM::FK_VFPV4);
719     else if (STI.hasVFP3())
720       ATS.emitFPU(STI.hasD16()
721                   // +d16
722                   ? (STI.isFPOnlySP()
723                      ? (STI.hasFP16() ? ARM::FK_VFPV3XD_FP16 : ARM::FK_VFPV3XD)
724                      : (STI.hasFP16() ? ARM::FK_VFPV3_D16_FP16 : ARM::FK_VFPV3_D16))
725                   // -d16
726                   : (STI.hasFP16() ? ARM::FK_VFPV3_FP16 : ARM::FK_VFPV3));
727     else if (STI.hasVFP2())
728       ATS.emitFPU(ARM::FK_VFPV2);
729   }
730 
731   if (isPositionIndependent()) {
732     // PIC specific attributes.
733     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
734                       ARMBuildAttrs::AddressRWPCRel);
735     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RO_data,
736                       ARMBuildAttrs::AddressROPCRel);
737     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
738                       ARMBuildAttrs::AddressGOT);
739   } else {
740     // Allow direct addressing of imported data for all other relocation models.
741     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
742                       ARMBuildAttrs::AddressDirect);
743   }
744 
745   // Signal various FP modes.
746   if (!TM.Options.UnsafeFPMath) {
747     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
748                       ARMBuildAttrs::IEEEDenormals);
749     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions, ARMBuildAttrs::Allowed);
750 
751     // If the user has permitted this code to choose the IEEE 754
752     // rounding at run-time, emit the rounding attribute.
753     if (TM.Options.HonorSignDependentRoundingFPMathOption)
754       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_rounding, ARMBuildAttrs::Allowed);
755   } else {
756     if (!STI.hasVFP2()) {
757       // When the target doesn't have an FPU (by design or
758       // intention), the assumptions made on the software support
759       // mirror that of the equivalent hardware support *if it
760       // existed*. For v7 and better we indicate that denormals are
761       // flushed preserving sign, and for V6 we indicate that
762       // denormals are flushed to positive zero.
763       if (STI.hasV7Ops())
764         ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
765                           ARMBuildAttrs::PreserveFPSign);
766     } else if (STI.hasVFP3()) {
767       // In VFPv4, VFPv4U, VFPv3, or VFPv3U, it is preserved. That is,
768       // the sign bit of the zero matches the sign bit of the input or
769       // result that is being flushed to zero.
770       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
771                         ARMBuildAttrs::PreserveFPSign);
772     }
773     // For VFPv2 implementations it is implementation defined as
774     // to whether denormals are flushed to positive zero or to
775     // whatever the sign of zero is (ARM v7AR ARM 2.7.5). Historically
776     // LLVM has chosen to flush this to positive zero (most likely for
777     // GCC compatibility), so that's the chosen value here (the
778     // absence of its emission implies zero).
779   }
780 
781   // TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath is the
782   // equivalent of GCC's -ffinite-math-only flag.
783   if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
784     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
785                       ARMBuildAttrs::Allowed);
786   else
787     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
788                       ARMBuildAttrs::AllowIEE754);
789 
790   if (STI.allowsUnalignedMem())
791     ATS.emitAttribute(ARMBuildAttrs::CPU_unaligned_access,
792                       ARMBuildAttrs::Allowed);
793   else
794     ATS.emitAttribute(ARMBuildAttrs::CPU_unaligned_access,
795                       ARMBuildAttrs::Not_Allowed);
796 
797   // FIXME: add more flags to ARMBuildAttributes.h
798   // 8-bytes alignment stuff.
799   ATS.emitAttribute(ARMBuildAttrs::ABI_align_needed, 1);
800   ATS.emitAttribute(ARMBuildAttrs::ABI_align_preserved, 1);
801 
802   // ABI_HardFP_use attribute to indicate single precision FP.
803   if (STI.isFPOnlySP())
804     ATS.emitAttribute(ARMBuildAttrs::ABI_HardFP_use,
805                       ARMBuildAttrs::HardFPSinglePrecision);
806 
807   // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
808   if (STI.isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard)
809     ATS.emitAttribute(ARMBuildAttrs::ABI_VFP_args, ARMBuildAttrs::HardFPAAPCS);
810 
811   // FIXME: Should we signal R9 usage?
812 
813   if (STI.hasFP16())
814     ATS.emitAttribute(ARMBuildAttrs::FP_HP_extension, ARMBuildAttrs::AllowHPFP);
815 
816   // FIXME: To support emitting this build attribute as GCC does, the
817   // -mfp16-format option and associated plumbing must be
818   // supported. For now the __fp16 type is exposed by default, so this
819   // attribute should be emitted with value 1.
820   ATS.emitAttribute(ARMBuildAttrs::ABI_FP_16bit_format,
821                     ARMBuildAttrs::FP16FormatIEEE);
822 
823   if (STI.hasMPExtension())
824     ATS.emitAttribute(ARMBuildAttrs::MPextension_use, ARMBuildAttrs::AllowMP);
825 
826   // Hardware divide in ARM mode is part of base arch, starting from ARMv8.
827   // If only Thumb hwdiv is present, it must also be in base arch (ARMv7-R/M).
828   // It is not possible to produce DisallowDIV: if hwdiv is present in the base
829   // arch, supplying -hwdiv downgrades the effective arch, via ClearImpliedBits.
830   // AllowDIVExt is only emitted if hwdiv isn't available in the base arch;
831   // otherwise, the default value (AllowDIVIfExists) applies.
832   if (STI.hasDivideInARMMode() && !STI.hasV8Ops())
833     ATS.emitAttribute(ARMBuildAttrs::DIV_use, ARMBuildAttrs::AllowDIVExt);
834 
835   if (STI.hasDSP() && isV8M(&STI))
836     ATS.emitAttribute(ARMBuildAttrs::DSP_extension, ARMBuildAttrs::Allowed);
837 
838   if (MMI) {
839     if (const Module *SourceModule = MMI->getModule()) {
840       // ABI_PCS_wchar_t to indicate wchar_t width
841       // FIXME: There is no way to emit value 0 (wchar_t prohibited).
842       if (auto WCharWidthValue = mdconst::extract_or_null<ConstantInt>(
843               SourceModule->getModuleFlag("wchar_size"))) {
844         int WCharWidth = WCharWidthValue->getZExtValue();
845         assert((WCharWidth == 2 || WCharWidth == 4) &&
846                "wchar_t width must be 2 or 4 bytes");
847         ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_wchar_t, WCharWidth);
848       }
849 
850       // ABI_enum_size to indicate enum width
851       // FIXME: There is no way to emit value 0 (enums prohibited) or value 3
852       //        (all enums contain a value needing 32 bits to encode).
853       if (auto EnumWidthValue = mdconst::extract_or_null<ConstantInt>(
854               SourceModule->getModuleFlag("min_enum_size"))) {
855         int EnumWidth = EnumWidthValue->getZExtValue();
856         assert((EnumWidth == 1 || EnumWidth == 4) &&
857                "Minimum enum width must be 1 or 4 bytes");
858         int EnumBuildAttr = EnumWidth == 1 ? 1 : 2;
859         ATS.emitAttribute(ARMBuildAttrs::ABI_enum_size, EnumBuildAttr);
860       }
861     }
862   }
863 
864   // TODO: We currently only support either reserving the register, or treating
865   // it as another callee-saved register, but not as SB or a TLS pointer; It
866   // would instead be nicer to push this from the frontend as metadata, as we do
867   // for the wchar and enum size tags
868   if (STI.isR9Reserved())
869     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use, ARMBuildAttrs::R9Reserved);
870   else
871     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use, ARMBuildAttrs::R9IsGPR);
872 
873   if (STI.hasTrustZone() && STI.hasVirtualization())
874     ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
875                       ARMBuildAttrs::AllowTZVirtualization);
876   else if (STI.hasTrustZone())
877     ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
878                       ARMBuildAttrs::AllowTZ);
879   else if (STI.hasVirtualization())
880     ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
881                       ARMBuildAttrs::AllowVirtualization);
882 }
883 
884 //===----------------------------------------------------------------------===//
885 
886 static MCSymbol *getPICLabel(const char *Prefix, unsigned FunctionNumber,
887                              unsigned LabelId, MCContext &Ctx) {
888 
889   MCSymbol *Label = Ctx.getOrCreateSymbol(Twine(Prefix)
890                        + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
891   return Label;
892 }
893 
894 static MCSymbolRefExpr::VariantKind
895 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
896   switch (Modifier) {
897   case ARMCP::no_modifier:
898     return MCSymbolRefExpr::VK_None;
899   case ARMCP::TLSGD:
900     return MCSymbolRefExpr::VK_TLSGD;
901   case ARMCP::TPOFF:
902     return MCSymbolRefExpr::VK_TPOFF;
903   case ARMCP::GOTTPOFF:
904     return MCSymbolRefExpr::VK_GOTTPOFF;
905   case ARMCP::GOT_PREL:
906     return MCSymbolRefExpr::VK_ARM_GOT_PREL;
907   case ARMCP::SECREL:
908     return MCSymbolRefExpr::VK_SECREL;
909   }
910   llvm_unreachable("Invalid ARMCPModifier!");
911 }
912 
913 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
914                                         unsigned char TargetFlags) {
915   if (Subtarget->isTargetMachO()) {
916     bool IsIndirect = (TargetFlags & ARMII::MO_NONLAZY) &&
917       Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel());
918 
919     if (!IsIndirect)
920       return getSymbol(GV);
921 
922     // FIXME: Remove this when Darwin transition to @GOT like syntax.
923     MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
924     MachineModuleInfoMachO &MMIMachO =
925       MMI->getObjFileInfo<MachineModuleInfoMachO>();
926     MachineModuleInfoImpl::StubValueTy &StubSym =
927         GV->isThreadLocal() ? MMIMachO.getThreadLocalGVStubEntry(MCSym)
928                             : MMIMachO.getGVStubEntry(MCSym);
929 
930     if (!StubSym.getPointer())
931       StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
932                                                    !GV->hasInternalLinkage());
933     return MCSym;
934   } else if (Subtarget->isTargetCOFF()) {
935     assert(Subtarget->isTargetWindows() &&
936            "Windows is the only supported COFF target");
937 
938     bool IsIndirect = (TargetFlags & ARMII::MO_DLLIMPORT);
939     if (!IsIndirect)
940       return getSymbol(GV);
941 
942     SmallString<128> Name;
943     Name = "__imp_";
944     getNameWithPrefix(Name, GV);
945 
946     return OutContext.getOrCreateSymbol(Name);
947   } else if (Subtarget->isTargetELF()) {
948     return getSymbol(GV);
949   }
950   llvm_unreachable("unexpected target");
951 }
952 
953 void ARMAsmPrinter::
954 EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
955   const DataLayout &DL = getDataLayout();
956   int Size = DL.getTypeAllocSize(MCPV->getType());
957 
958   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
959 
960   MCSymbol *MCSym;
961   if (ACPV->isLSDA()) {
962     MCSym = getCurExceptionSym();
963   } else if (ACPV->isBlockAddress()) {
964     const BlockAddress *BA =
965       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
966     MCSym = GetBlockAddressSymbol(BA);
967   } else if (ACPV->isGlobalValue()) {
968     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
969 
970     // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
971     // flag the global as MO_NONLAZY.
972     unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
973     MCSym = GetARMGVSymbol(GV, TF);
974   } else if (ACPV->isMachineBasicBlock()) {
975     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
976     MCSym = MBB->getSymbol();
977   } else {
978     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
979     const char *Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
980     MCSym = GetExternalSymbolSymbol(Sym);
981   }
982 
983   // Create an MCSymbol for the reference.
984   const MCExpr *Expr =
985     MCSymbolRefExpr::create(MCSym, getModifierVariantKind(ACPV->getModifier()),
986                             OutContext);
987 
988   if (ACPV->getPCAdjustment()) {
989     MCSymbol *PCLabel =
990         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
991                     ACPV->getLabelId(), OutContext);
992     const MCExpr *PCRelExpr = MCSymbolRefExpr::create(PCLabel, OutContext);
993     PCRelExpr =
994       MCBinaryExpr::createAdd(PCRelExpr,
995                               MCConstantExpr::create(ACPV->getPCAdjustment(),
996                                                      OutContext),
997                               OutContext);
998     if (ACPV->mustAddCurrentAddress()) {
999       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
1000       // label, so just emit a local label end reference that instead.
1001       MCSymbol *DotSym = OutContext.createTempSymbol();
1002       OutStreamer->EmitLabel(DotSym);
1003       const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
1004       PCRelExpr = MCBinaryExpr::createSub(PCRelExpr, DotExpr, OutContext);
1005     }
1006     Expr = MCBinaryExpr::createSub(Expr, PCRelExpr, OutContext);
1007   }
1008   OutStreamer->EmitValue(Expr, Size);
1009 }
1010 
1011 void ARMAsmPrinter::EmitJumpTableAddrs(const MachineInstr *MI) {
1012   const MachineOperand &MO1 = MI->getOperand(1);
1013   unsigned JTI = MO1.getIndex();
1014 
1015   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
1016   // ARM mode tables.
1017   EmitAlignment(2);
1018 
1019   // Emit a label for the jump table.
1020   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1021   OutStreamer->EmitLabel(JTISymbol);
1022 
1023   // Mark the jump table as data-in-code.
1024   OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1025 
1026   // Emit each entry of the table.
1027   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1028   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1029   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1030 
1031   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
1032     MachineBasicBlock *MBB = JTBBs[i];
1033     // Construct an MCExpr for the entry. We want a value of the form:
1034     // (BasicBlockAddr - TableBeginAddr)
1035     //
1036     // For example, a table with entries jumping to basic blocks BB0 and BB1
1037     // would look like:
1038     // LJTI_0_0:
1039     //    .word (LBB0 - LJTI_0_0)
1040     //    .word (LBB1 - LJTI_0_0)
1041     const MCExpr *Expr = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1042 
1043     if (isPositionIndependent())
1044       Expr = MCBinaryExpr::createSub(Expr, MCSymbolRefExpr::create(JTISymbol,
1045                                                                    OutContext),
1046                                      OutContext);
1047     // If we're generating a table of Thumb addresses in static relocation
1048     // model, we need to add one to keep interworking correctly.
1049     else if (AFI->isThumbFunction())
1050       Expr = MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(1,OutContext),
1051                                      OutContext);
1052     OutStreamer->EmitValue(Expr, 4);
1053   }
1054   // Mark the end of jump table data-in-code region.
1055   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1056 }
1057 
1058 void ARMAsmPrinter::EmitJumpTableInsts(const MachineInstr *MI) {
1059   const MachineOperand &MO1 = MI->getOperand(1);
1060   unsigned JTI = MO1.getIndex();
1061 
1062   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1063   OutStreamer->EmitLabel(JTISymbol);
1064 
1065   // Emit each entry of the table.
1066   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1067   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1068   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1069 
1070   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
1071     MachineBasicBlock *MBB = JTBBs[i];
1072     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1073                                                           OutContext);
1074     // If this isn't a TBB or TBH, the entries are direct branch instructions.
1075     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2B)
1076         .addExpr(MBBSymbolExpr)
1077         .addImm(ARMCC::AL)
1078         .addReg(0));
1079   }
1080 }
1081 
1082 void ARMAsmPrinter::EmitJumpTableTBInst(const MachineInstr *MI,
1083                                         unsigned OffsetWidth) {
1084   assert((OffsetWidth == 1 || OffsetWidth == 2) && "invalid tbb/tbh width");
1085   const MachineOperand &MO1 = MI->getOperand(1);
1086   unsigned JTI = MO1.getIndex();
1087 
1088   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1089   OutStreamer->EmitLabel(JTISymbol);
1090 
1091   // Emit each entry of the table.
1092   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1093   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1094   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1095 
1096   // Mark the jump table as data-in-code.
1097   OutStreamer->EmitDataRegion(OffsetWidth == 1 ? MCDR_DataRegionJT8
1098                                                : MCDR_DataRegionJT16);
1099 
1100   for (auto MBB : JTBBs) {
1101     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1102                                                           OutContext);
1103     // Otherwise it's an offset from the dispatch instruction. Construct an
1104     // MCExpr for the entry. We want a value of the form:
1105     // (BasicBlockAddr - TBBInstAddr + 4) / 2
1106     //
1107     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
1108     // would look like:
1109     // LJTI_0_0:
1110     //    .byte (LBB0 - (LCPI0_0 + 4)) / 2
1111     //    .byte (LBB1 - (LCPI0_0 + 4)) / 2
1112     // where LCPI0_0 is a label defined just before the TBB instruction using
1113     // this table.
1114     MCSymbol *TBInstPC = GetCPISymbol(MI->getOperand(0).getImm());
1115     const MCExpr *Expr = MCBinaryExpr::createAdd(
1116         MCSymbolRefExpr::create(TBInstPC, OutContext),
1117         MCConstantExpr::create(4, OutContext), OutContext);
1118     Expr = MCBinaryExpr::createSub(MBBSymbolExpr, Expr, OutContext);
1119     Expr = MCBinaryExpr::createDiv(Expr, MCConstantExpr::create(2, OutContext),
1120                                    OutContext);
1121     OutStreamer->EmitValue(Expr, OffsetWidth);
1122   }
1123   // Mark the end of jump table data-in-code region. 32-bit offsets use
1124   // actual branch instructions here, so we don't mark those as a data-region
1125   // at all.
1126   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1127 
1128   // Make sure the next instruction is 2-byte aligned.
1129   EmitAlignment(1);
1130 }
1131 
1132 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
1133   assert(MI->getFlag(MachineInstr::FrameSetup) &&
1134       "Only instruction which are involved into frame setup code are allowed");
1135 
1136   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1137   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1138   const MachineFunction &MF = *MI->getParent()->getParent();
1139   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
1140   const ARMFunctionInfo &AFI = *MF.getInfo<ARMFunctionInfo>();
1141 
1142   unsigned FramePtr = RegInfo->getFrameRegister(MF);
1143   unsigned Opc = MI->getOpcode();
1144   unsigned SrcReg, DstReg;
1145 
1146   if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
1147     // Two special cases:
1148     // 1) tPUSH does not have src/dst regs.
1149     // 2) for Thumb1 code we sometimes materialize the constant via constpool
1150     // load. Yes, this is pretty fragile, but for now I don't see better
1151     // way... :(
1152     SrcReg = DstReg = ARM::SP;
1153   } else {
1154     SrcReg = MI->getOperand(1).getReg();
1155     DstReg = MI->getOperand(0).getReg();
1156   }
1157 
1158   // Try to figure out the unwinding opcode out of src / dst regs.
1159   if (MI->mayStore()) {
1160     // Register saves.
1161     assert(DstReg == ARM::SP &&
1162            "Only stack pointer as a destination reg is supported");
1163 
1164     SmallVector<unsigned, 4> RegList;
1165     // Skip src & dst reg, and pred ops.
1166     unsigned StartOp = 2 + 2;
1167     // Use all the operands.
1168     unsigned NumOffset = 0;
1169 
1170     switch (Opc) {
1171     default:
1172       MI->dump();
1173       llvm_unreachable("Unsupported opcode for unwinding information");
1174     case ARM::tPUSH:
1175       // Special case here: no src & dst reg, but two extra imp ops.
1176       StartOp = 2; NumOffset = 2;
1177     case ARM::STMDB_UPD:
1178     case ARM::t2STMDB_UPD:
1179     case ARM::VSTMDDB_UPD:
1180       assert(SrcReg == ARM::SP &&
1181              "Only stack pointer as a source reg is supported");
1182       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1183            i != NumOps; ++i) {
1184         const MachineOperand &MO = MI->getOperand(i);
1185         // Actually, there should never be any impdef stuff here. Skip it
1186         // temporary to workaround PR11902.
1187         if (MO.isImplicit())
1188           continue;
1189         RegList.push_back(MO.getReg());
1190       }
1191       break;
1192     case ARM::STR_PRE_IMM:
1193     case ARM::STR_PRE_REG:
1194     case ARM::t2STR_PRE:
1195       assert(MI->getOperand(2).getReg() == ARM::SP &&
1196              "Only stack pointer as a source reg is supported");
1197       RegList.push_back(SrcReg);
1198       break;
1199     }
1200     if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM)
1201       ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1202   } else {
1203     // Changes of stack / frame pointer.
1204     if (SrcReg == ARM::SP) {
1205       int64_t Offset = 0;
1206       switch (Opc) {
1207       default:
1208         MI->dump();
1209         llvm_unreachable("Unsupported opcode for unwinding information");
1210       case ARM::MOVr:
1211       case ARM::tMOVr:
1212         Offset = 0;
1213         break;
1214       case ARM::ADDri:
1215       case ARM::t2ADDri:
1216         Offset = -MI->getOperand(2).getImm();
1217         break;
1218       case ARM::SUBri:
1219       case ARM::t2SUBri:
1220         Offset = MI->getOperand(2).getImm();
1221         break;
1222       case ARM::tSUBspi:
1223         Offset = MI->getOperand(2).getImm()*4;
1224         break;
1225       case ARM::tADDspi:
1226       case ARM::tADDrSPi:
1227         Offset = -MI->getOperand(2).getImm()*4;
1228         break;
1229       case ARM::tLDRpci: {
1230         // Grab the constpool index and check, whether it corresponds to
1231         // original or cloned constpool entry.
1232         unsigned CPI = MI->getOperand(1).getIndex();
1233         const MachineConstantPool *MCP = MF.getConstantPool();
1234         if (CPI >= MCP->getConstants().size())
1235           CPI = AFI.getOriginalCPIdx(CPI);
1236         assert(CPI != -1U && "Invalid constpool index");
1237 
1238         // Derive the actual offset.
1239         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1240         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1241         // FIXME: Check for user, it should be "add" instruction!
1242         Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1243         break;
1244       }
1245       }
1246 
1247       if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1248         if (DstReg == FramePtr && FramePtr != ARM::SP)
1249           // Set-up of the frame pointer. Positive values correspond to "add"
1250           // instruction.
1251           ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
1252         else if (DstReg == ARM::SP) {
1253           // Change of SP by an offset. Positive values correspond to "sub"
1254           // instruction.
1255           ATS.emitPad(Offset);
1256         } else {
1257           // Move of SP to a register.  Positive values correspond to an "add"
1258           // instruction.
1259           ATS.emitMovSP(DstReg, -Offset);
1260         }
1261       }
1262     } else if (DstReg == ARM::SP) {
1263       MI->dump();
1264       llvm_unreachable("Unsupported opcode for unwinding information");
1265     }
1266     else {
1267       MI->dump();
1268       llvm_unreachable("Unsupported opcode for unwinding information");
1269     }
1270   }
1271 }
1272 
1273 // Simple pseudo-instructions have their lowering (with expansion to real
1274 // instructions) auto-generated.
1275 #include "ARMGenMCPseudoLowering.inc"
1276 
1277 void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1278   const DataLayout &DL = getDataLayout();
1279   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1280   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1281 
1282   // If we just ended a constant pool, mark it as such.
1283   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1284     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1285     InConstantPool = false;
1286   }
1287 
1288   // Emit unwinding stuff for frame-related instructions
1289   if (Subtarget->isTargetEHABICompatible() &&
1290        MI->getFlag(MachineInstr::FrameSetup))
1291     EmitUnwindingInstruction(MI);
1292 
1293   // Do any auto-generated pseudo lowerings.
1294   if (emitPseudoExpansionLowering(*OutStreamer, MI))
1295     return;
1296 
1297   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1298          "Pseudo flag setting opcode should be expanded early");
1299 
1300   // Check for manual lowerings.
1301   unsigned Opc = MI->getOpcode();
1302   switch (Opc) {
1303   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1304   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1305   case ARM::LEApcrel:
1306   case ARM::tLEApcrel:
1307   case ARM::t2LEApcrel: {
1308     // FIXME: Need to also handle globals and externals
1309     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1310     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1311                                                ARM::t2LEApcrel ? ARM::t2ADR
1312                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1313                      : ARM::ADR))
1314       .addReg(MI->getOperand(0).getReg())
1315       .addExpr(MCSymbolRefExpr::create(CPISymbol, OutContext))
1316       // Add predicate operands.
1317       .addImm(MI->getOperand(2).getImm())
1318       .addReg(MI->getOperand(3).getReg()));
1319     return;
1320   }
1321   case ARM::LEApcrelJT:
1322   case ARM::tLEApcrelJT:
1323   case ARM::t2LEApcrelJT: {
1324     MCSymbol *JTIPICSymbol =
1325       GetARMJTIPICJumpTableLabel(MI->getOperand(1).getIndex());
1326     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1327                                                ARM::t2LEApcrelJT ? ARM::t2ADR
1328                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1329                      : ARM::ADR))
1330       .addReg(MI->getOperand(0).getReg())
1331       .addExpr(MCSymbolRefExpr::create(JTIPICSymbol, OutContext))
1332       // Add predicate operands.
1333       .addImm(MI->getOperand(2).getImm())
1334       .addReg(MI->getOperand(3).getReg()));
1335     return;
1336   }
1337   // Darwin call instructions are just normal call instructions with different
1338   // clobber semantics (they clobber R9).
1339   case ARM::BX_CALL: {
1340     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1341       .addReg(ARM::LR)
1342       .addReg(ARM::PC)
1343       // Add predicate operands.
1344       .addImm(ARMCC::AL)
1345       .addReg(0)
1346       // Add 's' bit operand (always reg0 for this)
1347       .addReg(0));
1348 
1349     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1350       .addReg(MI->getOperand(0).getReg()));
1351     return;
1352   }
1353   case ARM::tBX_CALL: {
1354     if (Subtarget->hasV5TOps())
1355       llvm_unreachable("Expected BLX to be selected for v5t+");
1356 
1357     // On ARM v4t, when doing a call from thumb mode, we need to ensure
1358     // that the saved lr has its LSB set correctly (the arch doesn't
1359     // have blx).
1360     // So here we generate a bl to a small jump pad that does bx rN.
1361     // The jump pads are emitted after the function body.
1362 
1363     unsigned TReg = MI->getOperand(0).getReg();
1364     MCSymbol *TRegSym = nullptr;
1365     for (unsigned i = 0, e = ThumbIndirectPads.size(); i < e; i++) {
1366       if (ThumbIndirectPads[i].first == TReg) {
1367         TRegSym = ThumbIndirectPads[i].second;
1368         break;
1369       }
1370     }
1371 
1372     if (!TRegSym) {
1373       TRegSym = OutContext.createTempSymbol();
1374       ThumbIndirectPads.push_back(std::make_pair(TReg, TRegSym));
1375     }
1376 
1377     // Create a link-saving branch to the Reg Indirect Jump Pad.
1378     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBL)
1379         // Predicate comes first here.
1380         .addImm(ARMCC::AL).addReg(0)
1381         .addExpr(MCSymbolRefExpr::create(TRegSym, OutContext)));
1382     return;
1383   }
1384   case ARM::BMOVPCRX_CALL: {
1385     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1386       .addReg(ARM::LR)
1387       .addReg(ARM::PC)
1388       // Add predicate operands.
1389       .addImm(ARMCC::AL)
1390       .addReg(0)
1391       // Add 's' bit operand (always reg0 for this)
1392       .addReg(0));
1393 
1394     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1395       .addReg(ARM::PC)
1396       .addReg(MI->getOperand(0).getReg())
1397       // Add predicate operands.
1398       .addImm(ARMCC::AL)
1399       .addReg(0)
1400       // Add 's' bit operand (always reg0 for this)
1401       .addReg(0));
1402     return;
1403   }
1404   case ARM::BMOVPCB_CALL: {
1405     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1406       .addReg(ARM::LR)
1407       .addReg(ARM::PC)
1408       // Add predicate operands.
1409       .addImm(ARMCC::AL)
1410       .addReg(0)
1411       // Add 's' bit operand (always reg0 for this)
1412       .addReg(0));
1413 
1414     const MachineOperand &Op = MI->getOperand(0);
1415     const GlobalValue *GV = Op.getGlobal();
1416     const unsigned TF = Op.getTargetFlags();
1417     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1418     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1419     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::Bcc)
1420       .addExpr(GVSymExpr)
1421       // Add predicate operands.
1422       .addImm(ARMCC::AL)
1423       .addReg(0));
1424     return;
1425   }
1426   case ARM::MOVi16_ga_pcrel:
1427   case ARM::t2MOVi16_ga_pcrel: {
1428     MCInst TmpInst;
1429     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1430     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1431 
1432     unsigned TF = MI->getOperand(1).getTargetFlags();
1433     const GlobalValue *GV = MI->getOperand(1).getGlobal();
1434     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1435     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1436 
1437     MCSymbol *LabelSym =
1438         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1439                     MI->getOperand(2).getImm(), OutContext);
1440     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1441     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1442     const MCExpr *PCRelExpr =
1443       ARMMCExpr::createLower16(MCBinaryExpr::createSub(GVSymExpr,
1444                                       MCBinaryExpr::createAdd(LabelSymExpr,
1445                                       MCConstantExpr::create(PCAdj, OutContext),
1446                                       OutContext), OutContext), OutContext);
1447       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1448 
1449     // Add predicate operands.
1450     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1451     TmpInst.addOperand(MCOperand::createReg(0));
1452     // Add 's' bit operand (always reg0 for this)
1453     TmpInst.addOperand(MCOperand::createReg(0));
1454     EmitToStreamer(*OutStreamer, TmpInst);
1455     return;
1456   }
1457   case ARM::MOVTi16_ga_pcrel:
1458   case ARM::t2MOVTi16_ga_pcrel: {
1459     MCInst TmpInst;
1460     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1461                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
1462     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1463     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1464 
1465     unsigned TF = MI->getOperand(2).getTargetFlags();
1466     const GlobalValue *GV = MI->getOperand(2).getGlobal();
1467     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1468     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1469 
1470     MCSymbol *LabelSym =
1471         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1472                     MI->getOperand(3).getImm(), OutContext);
1473     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1474     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1475     const MCExpr *PCRelExpr =
1476         ARMMCExpr::createUpper16(MCBinaryExpr::createSub(GVSymExpr,
1477                                    MCBinaryExpr::createAdd(LabelSymExpr,
1478                                       MCConstantExpr::create(PCAdj, OutContext),
1479                                           OutContext), OutContext), OutContext);
1480       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1481     // Add predicate operands.
1482     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1483     TmpInst.addOperand(MCOperand::createReg(0));
1484     // Add 's' bit operand (always reg0 for this)
1485     TmpInst.addOperand(MCOperand::createReg(0));
1486     EmitToStreamer(*OutStreamer, TmpInst);
1487     return;
1488   }
1489   case ARM::tPICADD: {
1490     // This is a pseudo op for a label + instruction sequence, which looks like:
1491     // LPC0:
1492     //     add r0, pc
1493     // This adds the address of LPC0 to r0.
1494 
1495     // Emit the label.
1496     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1497                                        getFunctionNumber(),
1498                                        MI->getOperand(2).getImm(), OutContext));
1499 
1500     // Form and emit the add.
1501     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1502       .addReg(MI->getOperand(0).getReg())
1503       .addReg(MI->getOperand(0).getReg())
1504       .addReg(ARM::PC)
1505       // Add predicate operands.
1506       .addImm(ARMCC::AL)
1507       .addReg(0));
1508     return;
1509   }
1510   case ARM::PICADD: {
1511     // This is a pseudo op for a label + instruction sequence, which looks like:
1512     // LPC0:
1513     //     add r0, pc, r0
1514     // This adds the address of LPC0 to r0.
1515 
1516     // Emit the label.
1517     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1518                                        getFunctionNumber(),
1519                                        MI->getOperand(2).getImm(), OutContext));
1520 
1521     // Form and emit the add.
1522     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1523       .addReg(MI->getOperand(0).getReg())
1524       .addReg(ARM::PC)
1525       .addReg(MI->getOperand(1).getReg())
1526       // Add predicate operands.
1527       .addImm(MI->getOperand(3).getImm())
1528       .addReg(MI->getOperand(4).getReg())
1529       // Add 's' bit operand (always reg0 for this)
1530       .addReg(0));
1531     return;
1532   }
1533   case ARM::PICSTR:
1534   case ARM::PICSTRB:
1535   case ARM::PICSTRH:
1536   case ARM::PICLDR:
1537   case ARM::PICLDRB:
1538   case ARM::PICLDRH:
1539   case ARM::PICLDRSB:
1540   case ARM::PICLDRSH: {
1541     // This is a pseudo op for a label + instruction sequence, which looks like:
1542     // LPC0:
1543     //     OP r0, [pc, r0]
1544     // The LCP0 label is referenced by a constant pool entry in order to get
1545     // a PC-relative address at the ldr instruction.
1546 
1547     // Emit the label.
1548     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1549                                        getFunctionNumber(),
1550                                        MI->getOperand(2).getImm(), OutContext));
1551 
1552     // Form and emit the load
1553     unsigned Opcode;
1554     switch (MI->getOpcode()) {
1555     default:
1556       llvm_unreachable("Unexpected opcode!");
1557     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1558     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1559     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1560     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1561     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1562     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1563     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1564     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1565     }
1566     EmitToStreamer(*OutStreamer, MCInstBuilder(Opcode)
1567       .addReg(MI->getOperand(0).getReg())
1568       .addReg(ARM::PC)
1569       .addReg(MI->getOperand(1).getReg())
1570       .addImm(0)
1571       // Add predicate operands.
1572       .addImm(MI->getOperand(3).getImm())
1573       .addReg(MI->getOperand(4).getReg()));
1574 
1575     return;
1576   }
1577   case ARM::CONSTPOOL_ENTRY: {
1578     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1579     /// in the function.  The first operand is the ID# for this instruction, the
1580     /// second is the index into the MachineConstantPool that this is, the third
1581     /// is the size in bytes of this constant pool entry.
1582     /// The required alignment is specified on the basic block holding this MI.
1583     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1584     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1585 
1586     // If this is the first entry of the pool, mark it.
1587     if (!InConstantPool) {
1588       OutStreamer->EmitDataRegion(MCDR_DataRegion);
1589       InConstantPool = true;
1590     }
1591 
1592     OutStreamer->EmitLabel(GetCPISymbol(LabelId));
1593 
1594     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1595     if (MCPE.isMachineConstantPoolEntry())
1596       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1597     else
1598       EmitGlobalConstant(DL, MCPE.Val.ConstVal);
1599     return;
1600   }
1601   case ARM::JUMPTABLE_ADDRS:
1602     EmitJumpTableAddrs(MI);
1603     return;
1604   case ARM::JUMPTABLE_INSTS:
1605     EmitJumpTableInsts(MI);
1606     return;
1607   case ARM::JUMPTABLE_TBB:
1608   case ARM::JUMPTABLE_TBH:
1609     EmitJumpTableTBInst(MI, MI->getOpcode() == ARM::JUMPTABLE_TBB ? 1 : 2);
1610     return;
1611   case ARM::t2BR_JT: {
1612     // Lower and emit the instruction itself, then the jump table following it.
1613     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1614       .addReg(ARM::PC)
1615       .addReg(MI->getOperand(0).getReg())
1616       // Add predicate operands.
1617       .addImm(ARMCC::AL)
1618       .addReg(0));
1619     return;
1620   }
1621   case ARM::t2TBB_JT:
1622   case ARM::t2TBH_JT: {
1623     unsigned Opc = MI->getOpcode() == ARM::t2TBB_JT ? ARM::t2TBB : ARM::t2TBH;
1624     // Lower and emit the PC label, then the instruction itself.
1625     OutStreamer->EmitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1626     EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1627                                      .addReg(MI->getOperand(0).getReg())
1628                                      .addReg(MI->getOperand(1).getReg())
1629                                      // Add predicate operands.
1630                                      .addImm(ARMCC::AL)
1631                                      .addReg(0));
1632     return;
1633   }
1634   case ARM::tBR_JTr:
1635   case ARM::BR_JTr: {
1636     // Lower and emit the instruction itself, then the jump table following it.
1637     // mov pc, target
1638     MCInst TmpInst;
1639     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1640       ARM::MOVr : ARM::tMOVr;
1641     TmpInst.setOpcode(Opc);
1642     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1643     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1644     // Add predicate operands.
1645     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1646     TmpInst.addOperand(MCOperand::createReg(0));
1647     // Add 's' bit operand (always reg0 for this)
1648     if (Opc == ARM::MOVr)
1649       TmpInst.addOperand(MCOperand::createReg(0));
1650     EmitToStreamer(*OutStreamer, TmpInst);
1651     return;
1652   }
1653   case ARM::BR_JTm: {
1654     // Lower and emit the instruction itself, then the jump table following it.
1655     // ldr pc, target
1656     MCInst TmpInst;
1657     if (MI->getOperand(1).getReg() == 0) {
1658       // literal offset
1659       TmpInst.setOpcode(ARM::LDRi12);
1660       TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1661       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1662       TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1663     } else {
1664       TmpInst.setOpcode(ARM::LDRrs);
1665       TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1666       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1667       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1668       TmpInst.addOperand(MCOperand::createImm(0));
1669     }
1670     // Add predicate operands.
1671     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1672     TmpInst.addOperand(MCOperand::createReg(0));
1673     EmitToStreamer(*OutStreamer, TmpInst);
1674     return;
1675   }
1676   case ARM::BR_JTadd: {
1677     // Lower and emit the instruction itself, then the jump table following it.
1678     // add pc, target, idx
1679     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1680       .addReg(ARM::PC)
1681       .addReg(MI->getOperand(0).getReg())
1682       .addReg(MI->getOperand(1).getReg())
1683       // Add predicate operands.
1684       .addImm(ARMCC::AL)
1685       .addReg(0)
1686       // Add 's' bit operand (always reg0 for this)
1687       .addReg(0));
1688     return;
1689   }
1690   case ARM::SPACE:
1691     OutStreamer->EmitZeros(MI->getOperand(1).getImm());
1692     return;
1693   case ARM::TRAP: {
1694     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1695     // FIXME: Remove this special case when they do.
1696     if (!Subtarget->isTargetMachO()) {
1697       uint32_t Val = 0xe7ffdefeUL;
1698       OutStreamer->AddComment("trap");
1699       ATS.emitInst(Val);
1700       return;
1701     }
1702     break;
1703   }
1704   case ARM::TRAPNaCl: {
1705     uint32_t Val = 0xe7fedef0UL;
1706     OutStreamer->AddComment("trap");
1707     ATS.emitInst(Val);
1708     return;
1709   }
1710   case ARM::tTRAP: {
1711     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1712     // FIXME: Remove this special case when they do.
1713     if (!Subtarget->isTargetMachO()) {
1714       uint16_t Val = 0xdefe;
1715       OutStreamer->AddComment("trap");
1716       ATS.emitInst(Val, 'n');
1717       return;
1718     }
1719     break;
1720   }
1721   case ARM::t2Int_eh_sjlj_setjmp:
1722   case ARM::t2Int_eh_sjlj_setjmp_nofp:
1723   case ARM::tInt_eh_sjlj_setjmp: {
1724     // Two incoming args: GPR:$src, GPR:$val
1725     // mov $val, pc
1726     // adds $val, #7
1727     // str $val, [$src, #4]
1728     // movs r0, #0
1729     // b LSJLJEH
1730     // movs r0, #1
1731     // LSJLJEH:
1732     unsigned SrcReg = MI->getOperand(0).getReg();
1733     unsigned ValReg = MI->getOperand(1).getReg();
1734     MCSymbol *Label = OutContext.createTempSymbol("SJLJEH", false, true);
1735     OutStreamer->AddComment("eh_setjmp begin");
1736     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1737       .addReg(ValReg)
1738       .addReg(ARM::PC)
1739       // Predicate.
1740       .addImm(ARMCC::AL)
1741       .addReg(0));
1742 
1743     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDi3)
1744       .addReg(ValReg)
1745       // 's' bit operand
1746       .addReg(ARM::CPSR)
1747       .addReg(ValReg)
1748       .addImm(7)
1749       // Predicate.
1750       .addImm(ARMCC::AL)
1751       .addReg(0));
1752 
1753     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tSTRi)
1754       .addReg(ValReg)
1755       .addReg(SrcReg)
1756       // The offset immediate is #4. The operand value is scaled by 4 for the
1757       // tSTR instruction.
1758       .addImm(1)
1759       // Predicate.
1760       .addImm(ARMCC::AL)
1761       .addReg(0));
1762 
1763     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1764       .addReg(ARM::R0)
1765       .addReg(ARM::CPSR)
1766       .addImm(0)
1767       // Predicate.
1768       .addImm(ARMCC::AL)
1769       .addReg(0));
1770 
1771     const MCExpr *SymbolExpr = MCSymbolRefExpr::create(Label, OutContext);
1772     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tB)
1773       .addExpr(SymbolExpr)
1774       .addImm(ARMCC::AL)
1775       .addReg(0));
1776 
1777     OutStreamer->AddComment("eh_setjmp end");
1778     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1779       .addReg(ARM::R0)
1780       .addReg(ARM::CPSR)
1781       .addImm(1)
1782       // Predicate.
1783       .addImm(ARMCC::AL)
1784       .addReg(0));
1785 
1786     OutStreamer->EmitLabel(Label);
1787     return;
1788   }
1789 
1790   case ARM::Int_eh_sjlj_setjmp_nofp:
1791   case ARM::Int_eh_sjlj_setjmp: {
1792     // Two incoming args: GPR:$src, GPR:$val
1793     // add $val, pc, #8
1794     // str $val, [$src, #+4]
1795     // mov r0, #0
1796     // add pc, pc, #0
1797     // mov r0, #1
1798     unsigned SrcReg = MI->getOperand(0).getReg();
1799     unsigned ValReg = MI->getOperand(1).getReg();
1800 
1801     OutStreamer->AddComment("eh_setjmp begin");
1802     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1803       .addReg(ValReg)
1804       .addReg(ARM::PC)
1805       .addImm(8)
1806       // Predicate.
1807       .addImm(ARMCC::AL)
1808       .addReg(0)
1809       // 's' bit operand (always reg0 for this).
1810       .addReg(0));
1811 
1812     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::STRi12)
1813       .addReg(ValReg)
1814       .addReg(SrcReg)
1815       .addImm(4)
1816       // Predicate.
1817       .addImm(ARMCC::AL)
1818       .addReg(0));
1819 
1820     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1821       .addReg(ARM::R0)
1822       .addImm(0)
1823       // Predicate.
1824       .addImm(ARMCC::AL)
1825       .addReg(0)
1826       // 's' bit operand (always reg0 for this).
1827       .addReg(0));
1828 
1829     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1830       .addReg(ARM::PC)
1831       .addReg(ARM::PC)
1832       .addImm(0)
1833       // Predicate.
1834       .addImm(ARMCC::AL)
1835       .addReg(0)
1836       // 's' bit operand (always reg0 for this).
1837       .addReg(0));
1838 
1839     OutStreamer->AddComment("eh_setjmp end");
1840     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1841       .addReg(ARM::R0)
1842       .addImm(1)
1843       // Predicate.
1844       .addImm(ARMCC::AL)
1845       .addReg(0)
1846       // 's' bit operand (always reg0 for this).
1847       .addReg(0));
1848     return;
1849   }
1850   case ARM::Int_eh_sjlj_longjmp: {
1851     // ldr sp, [$src, #8]
1852     // ldr $scratch, [$src, #4]
1853     // ldr r7, [$src]
1854     // bx $scratch
1855     unsigned SrcReg = MI->getOperand(0).getReg();
1856     unsigned ScratchReg = MI->getOperand(1).getReg();
1857     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1858       .addReg(ARM::SP)
1859       .addReg(SrcReg)
1860       .addImm(8)
1861       // Predicate.
1862       .addImm(ARMCC::AL)
1863       .addReg(0));
1864 
1865     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1866       .addReg(ScratchReg)
1867       .addReg(SrcReg)
1868       .addImm(4)
1869       // Predicate.
1870       .addImm(ARMCC::AL)
1871       .addReg(0));
1872 
1873     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1874       .addReg(ARM::R7)
1875       .addReg(SrcReg)
1876       .addImm(0)
1877       // Predicate.
1878       .addImm(ARMCC::AL)
1879       .addReg(0));
1880 
1881     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1882       .addReg(ScratchReg)
1883       // Predicate.
1884       .addImm(ARMCC::AL)
1885       .addReg(0));
1886     return;
1887   }
1888   case ARM::tInt_eh_sjlj_longjmp:
1889   case ARM::tInt_WIN_eh_sjlj_longjmp: {
1890     // ldr $scratch, [$src, #8]
1891     // mov sp, $scratch
1892     // ldr $scratch, [$src, #4]
1893     // ldr r7, [$src]
1894     // bx $scratch
1895     unsigned SrcReg = MI->getOperand(0).getReg();
1896     unsigned ScratchReg = MI->getOperand(1).getReg();
1897 
1898     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1899       .addReg(ScratchReg)
1900       .addReg(SrcReg)
1901       // The offset immediate is #8. The operand value is scaled by 4 for the
1902       // tLDR instruction.
1903       .addImm(2)
1904       // Predicate.
1905       .addImm(ARMCC::AL)
1906       .addReg(0));
1907 
1908     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1909       .addReg(ARM::SP)
1910       .addReg(ScratchReg)
1911       // Predicate.
1912       .addImm(ARMCC::AL)
1913       .addReg(0));
1914 
1915     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1916       .addReg(ScratchReg)
1917       .addReg(SrcReg)
1918       .addImm(1)
1919       // Predicate.
1920       .addImm(ARMCC::AL)
1921       .addReg(0));
1922 
1923     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1924       .addReg(Opc == ARM::tInt_WIN_eh_sjlj_longjmp ? ARM::R11 : ARM::R7)
1925       .addReg(SrcReg)
1926       .addImm(0)
1927       // Predicate.
1928       .addImm(ARMCC::AL)
1929       .addReg(0));
1930 
1931     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
1932       .addReg(ScratchReg)
1933       // Predicate.
1934       .addImm(ARMCC::AL)
1935       .addReg(0));
1936     return;
1937   }
1938   }
1939 
1940   MCInst TmpInst;
1941   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
1942 
1943   EmitToStreamer(*OutStreamer, TmpInst);
1944 }
1945 
1946 //===----------------------------------------------------------------------===//
1947 // Target Registry Stuff
1948 //===----------------------------------------------------------------------===//
1949 
1950 // Force static initialization.
1951 extern "C" void LLVMInitializeARMAsmPrinter() {
1952   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMLETarget);
1953   RegisterAsmPrinter<ARMAsmPrinter> Y(TheARMBETarget);
1954   RegisterAsmPrinter<ARMAsmPrinter> A(TheThumbLETarget);
1955   RegisterAsmPrinter<ARMAsmPrinter> B(TheThumbBETarget);
1956 }
1957