1 //===-- SystemZTargetMachine.cpp - Define TargetMachine for SystemZ -------===//
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 "SystemZTargetMachine.h"
11 #include "MCTargetDesc/SystemZMCTargetDesc.h"
12 #include "SystemZ.h"
13 #include "SystemZMachineScheduler.h"
14 #include "SystemZTargetTransformInfo.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
22 #include "llvm/CodeGen/TargetPassConfig.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/Support/CodeGen.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Target/TargetLoweringObjectFile.h"
27 #include "llvm/Transforms/Scalar.h"
28 #include <string>
29 
30 using namespace llvm;
31 
LLVMInitializeSystemZTarget()32 extern "C" void LLVMInitializeSystemZTarget() {
33   // Register the target.
34   RegisterTargetMachine<SystemZTargetMachine> X(getTheSystemZTarget());
35 }
36 
37 // Determine whether we use the vector ABI.
UsesVectorABI(StringRef CPU,StringRef FS)38 static bool UsesVectorABI(StringRef CPU, StringRef FS) {
39   // We use the vector ABI whenever the vector facility is avaiable.
40   // This is the case by default if CPU is z13 or later, and can be
41   // overridden via "[+-]vector" feature string elements.
42   bool VectorABI = true;
43   if (CPU.empty() || CPU == "generic" ||
44       CPU == "z10" || CPU == "z196" || CPU == "zEC12")
45     VectorABI = false;
46 
47   SmallVector<StringRef, 3> Features;
48   FS.split(Features, ',', -1, false /* KeepEmpty */);
49   for (auto &Feature : Features) {
50     if (Feature == "vector" || Feature == "+vector")
51       VectorABI = true;
52     if (Feature == "-vector")
53       VectorABI = false;
54   }
55 
56   return VectorABI;
57 }
58 
computeDataLayout(const Triple & TT,StringRef CPU,StringRef FS)59 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
60                                      StringRef FS) {
61   bool VectorABI = UsesVectorABI(CPU, FS);
62   std::string Ret;
63 
64   // Big endian.
65   Ret += "E";
66 
67   // Data mangling.
68   Ret += DataLayout::getManglingComponent(TT);
69 
70   // Make sure that global data has at least 16 bits of alignment by
71   // default, so that we can refer to it using LARL.  We don't have any
72   // special requirements for stack variables though.
73   Ret += "-i1:8:16-i8:8:16";
74 
75   // 64-bit integers are naturally aligned.
76   Ret += "-i64:64";
77 
78   // 128-bit floats are aligned only to 64 bits.
79   Ret += "-f128:64";
80 
81   // When using the vector ABI, 128-bit vectors are also aligned to 64 bits.
82   if (VectorABI)
83     Ret += "-v128:64";
84 
85   // We prefer 16 bits of aligned for all globals; see above.
86   Ret += "-a:8:16";
87 
88   // Integer registers are 32 or 64 bits.
89   Ret += "-n32:64";
90 
91   return Ret;
92 }
93 
getEffectiveRelocModel(Optional<Reloc::Model> RM)94 static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
95   // Static code is suitable for use in a dynamic executable; there is no
96   // separate DynamicNoPIC model.
97   if (!RM.hasValue() || *RM == Reloc::DynamicNoPIC)
98     return Reloc::Static;
99   return *RM;
100 }
101 
102 // For SystemZ we define the models as follows:
103 //
104 // Small:  BRASL can call any function and will use a stub if necessary.
105 //         Locally-binding symbols will always be in range of LARL.
106 //
107 // Medium: BRASL can call any function and will use a stub if necessary.
108 //         GOT slots and locally-defined text will always be in range
109 //         of LARL, but other symbols might not be.
110 //
111 // Large:  Equivalent to Medium for now.
112 //
113 // Kernel: Equivalent to Medium for now.
114 //
115 // This means that any PIC module smaller than 4GB meets the
116 // requirements of Small, so Small seems like the best default there.
117 //
118 // All symbols bind locally in a non-PIC module, so the choice is less
119 // obvious.  There are two cases:
120 //
121 // - When creating an executable, PLTs and copy relocations allow
122 //   us to treat external symbols as part of the executable.
123 //   Any executable smaller than 4GB meets the requirements of Small,
124 //   so that seems like the best default.
125 //
126 // - When creating JIT code, stubs will be in range of BRASL if the
127 //   image is less than 4GB in size.  GOT entries will likewise be
128 //   in range of LARL.  However, the JIT environment has no equivalent
129 //   of copy relocs, so locally-binding data symbols might not be in
130 //   the range of LARL.  We need the Medium model in that case.
getEffectiveCodeModel(Optional<CodeModel::Model> CM,Reloc::Model RM,bool JIT)131 static CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM,
132                                               Reloc::Model RM, bool JIT) {
133   if (CM)
134     return *CM;
135   if (JIT)
136     return RM == Reloc::PIC_ ? CodeModel::Small : CodeModel::Medium;
137   return CodeModel::Small;
138 }
139 
SystemZTargetMachine(const Target & T,const Triple & TT,StringRef CPU,StringRef FS,const TargetOptions & Options,Optional<Reloc::Model> RM,Optional<CodeModel::Model> CM,CodeGenOpt::Level OL,bool JIT)140 SystemZTargetMachine::SystemZTargetMachine(const Target &T, const Triple &TT,
141                                            StringRef CPU, StringRef FS,
142                                            const TargetOptions &Options,
143                                            Optional<Reloc::Model> RM,
144                                            Optional<CodeModel::Model> CM,
145                                            CodeGenOpt::Level OL, bool JIT)
146     : LLVMTargetMachine(
147           T, computeDataLayout(TT, CPU, FS), TT, CPU, FS, Options,
148           getEffectiveRelocModel(RM),
149           getEffectiveCodeModel(CM, getEffectiveRelocModel(RM), JIT), OL),
150       TLOF(llvm::make_unique<TargetLoweringObjectFileELF>()),
151       Subtarget(TT, CPU, FS, *this) {
152   initAsmInfo();
153 }
154 
155 SystemZTargetMachine::~SystemZTargetMachine() = default;
156 
157 namespace {
158 
159 /// SystemZ Code Generator Pass Configuration Options.
160 class SystemZPassConfig : public TargetPassConfig {
161 public:
SystemZPassConfig(SystemZTargetMachine & TM,PassManagerBase & PM)162   SystemZPassConfig(SystemZTargetMachine &TM, PassManagerBase &PM)
163     : TargetPassConfig(TM, PM) {}
164 
getSystemZTargetMachine() const165   SystemZTargetMachine &getSystemZTargetMachine() const {
166     return getTM<SystemZTargetMachine>();
167   }
168 
169   ScheduleDAGInstrs *
createPostMachineScheduler(MachineSchedContext * C) const170   createPostMachineScheduler(MachineSchedContext *C) const override {
171     return new ScheduleDAGMI(C,
172                              llvm::make_unique<SystemZPostRASchedStrategy>(C),
173                              /*RemoveKillFlags=*/true);
174   }
175 
176   void addIRPasses() override;
177   bool addInstSelector() override;
178   bool addILPOpts() override;
179   void addPreSched2() override;
180   void addPreEmitPass() override;
181 };
182 
183 } // end anonymous namespace
184 
addIRPasses()185 void SystemZPassConfig::addIRPasses() {
186   if (getOptLevel() != CodeGenOpt::None) {
187     addPass(createSystemZTDCPass());
188     addPass(createLoopDataPrefetchPass());
189   }
190 
191   TargetPassConfig::addIRPasses();
192 }
193 
addInstSelector()194 bool SystemZPassConfig::addInstSelector() {
195   addPass(createSystemZISelDag(getSystemZTargetMachine(), getOptLevel()));
196 
197  if (getOptLevel() != CodeGenOpt::None)
198     addPass(createSystemZLDCleanupPass(getSystemZTargetMachine()));
199 
200   return false;
201 }
202 
addILPOpts()203 bool SystemZPassConfig::addILPOpts() {
204   addPass(&EarlyIfConverterID);
205   return true;
206 }
207 
addPreSched2()208 void SystemZPassConfig::addPreSched2() {
209   addPass(createSystemZExpandPseudoPass(getSystemZTargetMachine()));
210 
211   if (getOptLevel() != CodeGenOpt::None)
212     addPass(&IfConverterID);
213 }
214 
addPreEmitPass()215 void SystemZPassConfig::addPreEmitPass() {
216   // Do instruction shortening before compare elimination because some
217   // vector instructions will be shortened into opcodes that compare
218   // elimination recognizes.
219   if (getOptLevel() != CodeGenOpt::None)
220     addPass(createSystemZShortenInstPass(getSystemZTargetMachine()), false);
221 
222   // We eliminate comparisons here rather than earlier because some
223   // transformations can change the set of available CC values and we
224   // generally want those transformations to have priority.  This is
225   // especially true in the commonest case where the result of the comparison
226   // is used by a single in-range branch instruction, since we will then
227   // be able to fuse the compare and the branch instead.
228   //
229   // For example, two-address NILF can sometimes be converted into
230   // three-address RISBLG.  NILF produces a CC value that indicates whether
231   // the low word is zero, but RISBLG does not modify CC at all.  On the
232   // other hand, 64-bit ANDs like NILL can sometimes be converted to RISBG.
233   // The CC value produced by NILL isn't useful for our purposes, but the
234   // value produced by RISBG can be used for any comparison with zero
235   // (not just equality).  So there are some transformations that lose
236   // CC values (while still being worthwhile) and others that happen to make
237   // the CC result more useful than it was originally.
238   //
239   // Another reason is that we only want to use BRANCH ON COUNT in cases
240   // where we know that the count register is not going to be spilled.
241   //
242   // Doing it so late makes it more likely that a register will be reused
243   // between the comparison and the branch, but it isn't clear whether
244   // preventing that would be a win or not.
245   if (getOptLevel() != CodeGenOpt::None)
246     addPass(createSystemZElimComparePass(getSystemZTargetMachine()), false);
247   addPass(createSystemZLongBranchPass(getSystemZTargetMachine()));
248 
249   // Do final scheduling after all other optimizations, to get an
250   // optimal input for the decoder (branch relaxation must happen
251   // after block placement).
252   if (getOptLevel() != CodeGenOpt::None)
253     addPass(&PostMachineSchedulerID);
254 }
255 
createPassConfig(PassManagerBase & PM)256 TargetPassConfig *SystemZTargetMachine::createPassConfig(PassManagerBase &PM) {
257   return new SystemZPassConfig(*this, PM);
258 }
259 
260 TargetTransformInfo
getTargetTransformInfo(const Function & F)261 SystemZTargetMachine::getTargetTransformInfo(const Function &F) {
262   return TargetTransformInfo(SystemZTTIImpl(this, F));
263 }
264