1 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to NVPTX assembly language.
13 //===----------------------------------------------------------------------===//
15 #include "NVPTXAsmPrinter.h"
16 #include "InstPrinter/NVPTXInstPrinter.h"
17 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
19 #include "NVPTXInstrInfo.h"
20 #include "NVPTXMachineFunctionInfo.h"
21 #include "NVPTXMCExpr.h"
22 #include "NVPTXRegisterInfo.h"
23 #include "NVPTXTargetMachine.h"
24 #include "NVPTXUtilities.h"
25 #include "cl_common_defines.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Mangler.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TimeValue.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
51 #define DEPOTNAME "__local_depot"
54 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
55 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
59 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
60 cl::desc("NVPTX Specific: Emit source line in ptx file"),
64 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
66 void DiscoverDependentGlobals(const Value *V,
67 DenseSet<const GlobalVariable *> &Globals) {
68 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
71 if (const User *U = dyn_cast<User>(V)) {
72 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
73 DiscoverDependentGlobals(U->getOperand(i), Globals);
79 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
80 /// instances to be emitted, but only after any dependents have been added
82 void VisitGlobalVariableForEmission(
83 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
84 DenseSet<const GlobalVariable *> &Visited,
85 DenseSet<const GlobalVariable *> &Visiting) {
86 // Have we already visited this one?
87 if (Visited.count(GV))
90 // Do we have a circular dependency?
91 if (Visiting.count(GV))
92 report_fatal_error("Circular dependency found in global variable set");
94 // Start visiting this global
97 // Make sure we visit all dependents first
98 DenseSet<const GlobalVariable *> Others;
99 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
100 DiscoverDependentGlobals(GV->getOperand(i), Others);
102 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
105 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
107 // Now we can visit ourself
114 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
115 // cannot just link to the existing version.
116 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
118 using namespace nvptx;
119 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
120 MCContext &Ctx = AP.OutContext;
122 if (CV->isNullValue() || isa<UndefValue>(CV))
123 return MCConstantExpr::Create(0, Ctx);
125 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
126 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
128 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
129 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
131 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
132 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
134 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
136 llvm_unreachable("Unknown constant value to lower!");
138 switch (CE->getOpcode()) {
140 // If the code isn't optimized, there may be outstanding folding
141 // opportunities. Attempt to fold the expression using DataLayout as a
142 // last resort before giving up.
143 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
145 return LowerConstant(C, AP);
147 // Otherwise report the problem to the user.
150 raw_string_ostream OS(S);
151 OS << "Unsupported expression in static initializer: ";
152 CE->printAsOperand(OS, /*PrintType=*/ false,
153 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
154 report_fatal_error(OS.str());
156 case Instruction::AddrSpaceCast: {
157 // Strip any addrspace(1)->addrspace(0) addrspace casts. These will be
158 // handled by the generic() logic in the MCExpr printer
159 PointerType *DstTy = cast<PointerType>(CE->getType());
160 PointerType *SrcTy = cast<PointerType>(CE->getOperand(0)->getType());
161 if (SrcTy->getAddressSpace() == 1 && DstTy->getAddressSpace() == 0) {
162 return LowerConstant(cast<const Constant>(CE->getOperand(0)), AP);
165 raw_string_ostream OS(S);
166 OS << "Unsupported expression in static initializer: ";
167 CE->printAsOperand(OS, /*PrintType=*/ false,
168 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
169 report_fatal_error(OS.str());
171 case Instruction::GetElementPtr: {
172 const DataLayout &TD = *AP.TM.getDataLayout();
173 // Generate a symbolic expression for the byte address
174 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
175 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
177 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
181 int64_t Offset = OffsetAI.getSExtValue();
182 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
186 case Instruction::Trunc:
187 // We emit the value and depend on the assembler to truncate the generated
188 // expression properly. This is important for differences between
189 // blockaddress labels. Since the two labels are in the same function, it
190 // is reasonable to treat their delta as a 32-bit value.
192 case Instruction::BitCast:
193 return LowerConstant(CE->getOperand(0), AP);
195 case Instruction::IntToPtr: {
196 const DataLayout &TD = *AP.TM.getDataLayout();
197 // Handle casts to pointers by changing them into casts to the appropriate
198 // integer type. This promotes constant folding and simplifies this code.
199 Constant *Op = CE->getOperand(0);
200 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
202 return LowerConstant(Op, AP);
205 case Instruction::PtrToInt: {
206 const DataLayout &TD = *AP.TM.getDataLayout();
207 // Support only foldable casts to/from pointers that can be eliminated by
208 // changing the pointer to the appropriately sized integer type.
209 Constant *Op = CE->getOperand(0);
210 Type *Ty = CE->getType();
212 const MCExpr *OpExpr = LowerConstant(Op, AP);
214 // We can emit the pointer value into this slot if the slot is an
215 // integer slot equal to the size of the pointer.
216 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
219 // Otherwise the pointer is smaller than the resultant integer, mask off
220 // the high bits so we are sure to get a proper truncation if the input is
222 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
223 const MCExpr *MaskExpr =
224 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
225 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
228 // The MC library also has a right-shift operator, but it isn't consistently
229 // signed or unsigned between different targets.
230 case Instruction::Add:
231 case Instruction::Sub:
232 case Instruction::Mul:
233 case Instruction::SDiv:
234 case Instruction::SRem:
235 case Instruction::Shl:
236 case Instruction::And:
237 case Instruction::Or:
238 case Instruction::Xor: {
239 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
240 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
241 switch (CE->getOpcode()) {
243 llvm_unreachable("Unknown binary operator constant cast expr");
244 case Instruction::Add:
245 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
246 case Instruction::Sub:
247 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
248 case Instruction::Mul:
249 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
250 case Instruction::SDiv:
251 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
252 case Instruction::SRem:
253 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
254 case Instruction::Shl:
255 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
256 case Instruction::And:
257 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
258 case Instruction::Or:
259 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
260 case Instruction::Xor:
261 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
267 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
268 if (!EmitLineNumbers)
273 DebugLoc curLoc = MI.getDebugLoc();
275 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
278 if (prevDebugLoc == curLoc)
281 prevDebugLoc = curLoc;
283 if (curLoc.isUnknown())
286 const MachineFunction *MF = MI.getParent()->getParent();
287 //const TargetMachine &TM = MF->getTarget();
289 const LLVMContext &ctx = MF->getFunction()->getContext();
290 DIScope Scope(curLoc.getScope(ctx));
292 assert((!Scope || Scope.isScope()) &&
293 "Scope of a DebugLoc should be null or a DIScope.");
297 StringRef fileName(Scope.getFilename());
298 StringRef dirName(Scope.getDirectory());
299 SmallString<128> FullPathName = dirName;
300 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
301 sys::path::append(FullPathName, fileName);
302 fileName = FullPathName.str();
305 if (filenameMap.find(fileName.str()) == filenameMap.end())
308 // Emit the line from the source file.
310 this->emitSrcInText(fileName.str(), curLoc.getLine());
312 std::stringstream temp;
313 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
314 << " " << curLoc.getCol();
315 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
318 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
319 SmallString<128> Str;
320 raw_svector_ostream OS(Str);
321 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
322 emitLineNumberAsDotLoc(*MI);
325 lowerToMCInst(MI, Inst);
326 EmitToStreamer(OutStreamer, Inst);
329 // Handle symbol backtracking for targets that do not support image handles
330 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
331 unsigned OpNo, MCOperand &MCOp) {
332 const MachineOperand &MO = MI->getOperand(OpNo);
334 switch (MI->getOpcode()) {
335 default: return false;
336 case NVPTX::TEX_1D_F32_I32:
337 case NVPTX::TEX_1D_F32_F32:
338 case NVPTX::TEX_1D_F32_F32_LEVEL:
339 case NVPTX::TEX_1D_F32_F32_GRAD:
340 case NVPTX::TEX_1D_I32_I32:
341 case NVPTX::TEX_1D_I32_F32:
342 case NVPTX::TEX_1D_I32_F32_LEVEL:
343 case NVPTX::TEX_1D_I32_F32_GRAD:
344 case NVPTX::TEX_1D_ARRAY_F32_I32:
345 case NVPTX::TEX_1D_ARRAY_F32_F32:
346 case NVPTX::TEX_1D_ARRAY_F32_F32_LEVEL:
347 case NVPTX::TEX_1D_ARRAY_F32_F32_GRAD:
348 case NVPTX::TEX_1D_ARRAY_I32_I32:
349 case NVPTX::TEX_1D_ARRAY_I32_F32:
350 case NVPTX::TEX_1D_ARRAY_I32_F32_LEVEL:
351 case NVPTX::TEX_1D_ARRAY_I32_F32_GRAD:
352 case NVPTX::TEX_2D_F32_I32:
353 case NVPTX::TEX_2D_F32_F32:
354 case NVPTX::TEX_2D_F32_F32_LEVEL:
355 case NVPTX::TEX_2D_F32_F32_GRAD:
356 case NVPTX::TEX_2D_I32_I32:
357 case NVPTX::TEX_2D_I32_F32:
358 case NVPTX::TEX_2D_I32_F32_LEVEL:
359 case NVPTX::TEX_2D_I32_F32_GRAD:
360 case NVPTX::TEX_2D_ARRAY_F32_I32:
361 case NVPTX::TEX_2D_ARRAY_F32_F32:
362 case NVPTX::TEX_2D_ARRAY_F32_F32_LEVEL:
363 case NVPTX::TEX_2D_ARRAY_F32_F32_GRAD:
364 case NVPTX::TEX_2D_ARRAY_I32_I32:
365 case NVPTX::TEX_2D_ARRAY_I32_F32:
366 case NVPTX::TEX_2D_ARRAY_I32_F32_LEVEL:
367 case NVPTX::TEX_2D_ARRAY_I32_F32_GRAD:
368 case NVPTX::TEX_3D_F32_I32:
369 case NVPTX::TEX_3D_F32_F32:
370 case NVPTX::TEX_3D_F32_F32_LEVEL:
371 case NVPTX::TEX_3D_F32_F32_GRAD:
372 case NVPTX::TEX_3D_I32_I32:
373 case NVPTX::TEX_3D_I32_F32:
374 case NVPTX::TEX_3D_I32_F32_LEVEL:
375 case NVPTX::TEX_3D_I32_F32_GRAD:
377 // This is a texture fetch, so operand 4 is a texref and operand 5 is
380 lowerImageHandleSymbol(MO.getImm(), MCOp);
384 lowerImageHandleSymbol(MO.getImm(), MCOp);
390 case NVPTX::SULD_1D_I8_TRAP:
391 case NVPTX::SULD_1D_I16_TRAP:
392 case NVPTX::SULD_1D_I32_TRAP:
393 case NVPTX::SULD_1D_ARRAY_I8_TRAP:
394 case NVPTX::SULD_1D_ARRAY_I16_TRAP:
395 case NVPTX::SULD_1D_ARRAY_I32_TRAP:
396 case NVPTX::SULD_2D_I8_TRAP:
397 case NVPTX::SULD_2D_I16_TRAP:
398 case NVPTX::SULD_2D_I32_TRAP:
399 case NVPTX::SULD_2D_ARRAY_I8_TRAP:
400 case NVPTX::SULD_2D_ARRAY_I16_TRAP:
401 case NVPTX::SULD_2D_ARRAY_I32_TRAP:
402 case NVPTX::SULD_3D_I8_TRAP:
403 case NVPTX::SULD_3D_I16_TRAP:
404 case NVPTX::SULD_3D_I32_TRAP: {
405 // This is a V1 surface load, so operand 1 is a surfref
407 lowerImageHandleSymbol(MO.getImm(), MCOp);
413 case NVPTX::SULD_1D_V2I8_TRAP:
414 case NVPTX::SULD_1D_V2I16_TRAP:
415 case NVPTX::SULD_1D_V2I32_TRAP:
416 case NVPTX::SULD_1D_ARRAY_V2I8_TRAP:
417 case NVPTX::SULD_1D_ARRAY_V2I16_TRAP:
418 case NVPTX::SULD_1D_ARRAY_V2I32_TRAP:
419 case NVPTX::SULD_2D_V2I8_TRAP:
420 case NVPTX::SULD_2D_V2I16_TRAP:
421 case NVPTX::SULD_2D_V2I32_TRAP:
422 case NVPTX::SULD_2D_ARRAY_V2I8_TRAP:
423 case NVPTX::SULD_2D_ARRAY_V2I16_TRAP:
424 case NVPTX::SULD_2D_ARRAY_V2I32_TRAP:
425 case NVPTX::SULD_3D_V2I8_TRAP:
426 case NVPTX::SULD_3D_V2I16_TRAP:
427 case NVPTX::SULD_3D_V2I32_TRAP: {
428 // This is a V2 surface load, so operand 2 is a surfref
430 lowerImageHandleSymbol(MO.getImm(), MCOp);
436 case NVPTX::SULD_1D_V4I8_TRAP:
437 case NVPTX::SULD_1D_V4I16_TRAP:
438 case NVPTX::SULD_1D_V4I32_TRAP:
439 case NVPTX::SULD_1D_ARRAY_V4I8_TRAP:
440 case NVPTX::SULD_1D_ARRAY_V4I16_TRAP:
441 case NVPTX::SULD_1D_ARRAY_V4I32_TRAP:
442 case NVPTX::SULD_2D_V4I8_TRAP:
443 case NVPTX::SULD_2D_V4I16_TRAP:
444 case NVPTX::SULD_2D_V4I32_TRAP:
445 case NVPTX::SULD_2D_ARRAY_V4I8_TRAP:
446 case NVPTX::SULD_2D_ARRAY_V4I16_TRAP:
447 case NVPTX::SULD_2D_ARRAY_V4I32_TRAP:
448 case NVPTX::SULD_3D_V4I8_TRAP:
449 case NVPTX::SULD_3D_V4I16_TRAP:
450 case NVPTX::SULD_3D_V4I32_TRAP: {
451 // This is a V4 surface load, so operand 4 is a surfref
453 lowerImageHandleSymbol(MO.getImm(), MCOp);
459 case NVPTX::SUST_B_1D_B8_TRAP:
460 case NVPTX::SUST_B_1D_B16_TRAP:
461 case NVPTX::SUST_B_1D_B32_TRAP:
462 case NVPTX::SUST_B_1D_V2B8_TRAP:
463 case NVPTX::SUST_B_1D_V2B16_TRAP:
464 case NVPTX::SUST_B_1D_V2B32_TRAP:
465 case NVPTX::SUST_B_1D_V4B8_TRAP:
466 case NVPTX::SUST_B_1D_V4B16_TRAP:
467 case NVPTX::SUST_B_1D_V4B32_TRAP:
468 case NVPTX::SUST_B_1D_ARRAY_B8_TRAP:
469 case NVPTX::SUST_B_1D_ARRAY_B16_TRAP:
470 case NVPTX::SUST_B_1D_ARRAY_B32_TRAP:
471 case NVPTX::SUST_B_1D_ARRAY_V2B8_TRAP:
472 case NVPTX::SUST_B_1D_ARRAY_V2B16_TRAP:
473 case NVPTX::SUST_B_1D_ARRAY_V2B32_TRAP:
474 case NVPTX::SUST_B_1D_ARRAY_V4B8_TRAP:
475 case NVPTX::SUST_B_1D_ARRAY_V4B16_TRAP:
476 case NVPTX::SUST_B_1D_ARRAY_V4B32_TRAP:
477 case NVPTX::SUST_B_2D_B8_TRAP:
478 case NVPTX::SUST_B_2D_B16_TRAP:
479 case NVPTX::SUST_B_2D_B32_TRAP:
480 case NVPTX::SUST_B_2D_V2B8_TRAP:
481 case NVPTX::SUST_B_2D_V2B16_TRAP:
482 case NVPTX::SUST_B_2D_V2B32_TRAP:
483 case NVPTX::SUST_B_2D_V4B8_TRAP:
484 case NVPTX::SUST_B_2D_V4B16_TRAP:
485 case NVPTX::SUST_B_2D_V4B32_TRAP:
486 case NVPTX::SUST_B_2D_ARRAY_B8_TRAP:
487 case NVPTX::SUST_B_2D_ARRAY_B16_TRAP:
488 case NVPTX::SUST_B_2D_ARRAY_B32_TRAP:
489 case NVPTX::SUST_B_2D_ARRAY_V2B8_TRAP:
490 case NVPTX::SUST_B_2D_ARRAY_V2B16_TRAP:
491 case NVPTX::SUST_B_2D_ARRAY_V2B32_TRAP:
492 case NVPTX::SUST_B_2D_ARRAY_V4B8_TRAP:
493 case NVPTX::SUST_B_2D_ARRAY_V4B16_TRAP:
494 case NVPTX::SUST_B_2D_ARRAY_V4B32_TRAP:
495 case NVPTX::SUST_B_3D_B8_TRAP:
496 case NVPTX::SUST_B_3D_B16_TRAP:
497 case NVPTX::SUST_B_3D_B32_TRAP:
498 case NVPTX::SUST_B_3D_V2B8_TRAP:
499 case NVPTX::SUST_B_3D_V2B16_TRAP:
500 case NVPTX::SUST_B_3D_V2B32_TRAP:
501 case NVPTX::SUST_B_3D_V4B8_TRAP:
502 case NVPTX::SUST_B_3D_V4B16_TRAP:
503 case NVPTX::SUST_B_3D_V4B32_TRAP:
504 case NVPTX::SUST_P_1D_B8_TRAP:
505 case NVPTX::SUST_P_1D_B16_TRAP:
506 case NVPTX::SUST_P_1D_B32_TRAP:
507 case NVPTX::SUST_P_1D_V2B8_TRAP:
508 case NVPTX::SUST_P_1D_V2B16_TRAP:
509 case NVPTX::SUST_P_1D_V2B32_TRAP:
510 case NVPTX::SUST_P_1D_V4B8_TRAP:
511 case NVPTX::SUST_P_1D_V4B16_TRAP:
512 case NVPTX::SUST_P_1D_V4B32_TRAP:
513 case NVPTX::SUST_P_1D_ARRAY_B8_TRAP:
514 case NVPTX::SUST_P_1D_ARRAY_B16_TRAP:
515 case NVPTX::SUST_P_1D_ARRAY_B32_TRAP:
516 case NVPTX::SUST_P_1D_ARRAY_V2B8_TRAP:
517 case NVPTX::SUST_P_1D_ARRAY_V2B16_TRAP:
518 case NVPTX::SUST_P_1D_ARRAY_V2B32_TRAP:
519 case NVPTX::SUST_P_1D_ARRAY_V4B8_TRAP:
520 case NVPTX::SUST_P_1D_ARRAY_V4B16_TRAP:
521 case NVPTX::SUST_P_1D_ARRAY_V4B32_TRAP:
522 case NVPTX::SUST_P_2D_B8_TRAP:
523 case NVPTX::SUST_P_2D_B16_TRAP:
524 case NVPTX::SUST_P_2D_B32_TRAP:
525 case NVPTX::SUST_P_2D_V2B8_TRAP:
526 case NVPTX::SUST_P_2D_V2B16_TRAP:
527 case NVPTX::SUST_P_2D_V2B32_TRAP:
528 case NVPTX::SUST_P_2D_V4B8_TRAP:
529 case NVPTX::SUST_P_2D_V4B16_TRAP:
530 case NVPTX::SUST_P_2D_V4B32_TRAP:
531 case NVPTX::SUST_P_2D_ARRAY_B8_TRAP:
532 case NVPTX::SUST_P_2D_ARRAY_B16_TRAP:
533 case NVPTX::SUST_P_2D_ARRAY_B32_TRAP:
534 case NVPTX::SUST_P_2D_ARRAY_V2B8_TRAP:
535 case NVPTX::SUST_P_2D_ARRAY_V2B16_TRAP:
536 case NVPTX::SUST_P_2D_ARRAY_V2B32_TRAP:
537 case NVPTX::SUST_P_2D_ARRAY_V4B8_TRAP:
538 case NVPTX::SUST_P_2D_ARRAY_V4B16_TRAP:
539 case NVPTX::SUST_P_2D_ARRAY_V4B32_TRAP:
540 case NVPTX::SUST_P_3D_B8_TRAP:
541 case NVPTX::SUST_P_3D_B16_TRAP:
542 case NVPTX::SUST_P_3D_B32_TRAP:
543 case NVPTX::SUST_P_3D_V2B8_TRAP:
544 case NVPTX::SUST_P_3D_V2B16_TRAP:
545 case NVPTX::SUST_P_3D_V2B32_TRAP:
546 case NVPTX::SUST_P_3D_V4B8_TRAP:
547 case NVPTX::SUST_P_3D_V4B16_TRAP:
548 case NVPTX::SUST_P_3D_V4B32_TRAP: {
549 // This is a surface store, so operand 0 is a surfref
551 lowerImageHandleSymbol(MO.getImm(), MCOp);
557 case NVPTX::TXQ_CHANNEL_ORDER:
558 case NVPTX::TXQ_CHANNEL_DATA_TYPE:
559 case NVPTX::TXQ_WIDTH:
560 case NVPTX::TXQ_HEIGHT:
561 case NVPTX::TXQ_DEPTH:
562 case NVPTX::TXQ_ARRAY_SIZE:
563 case NVPTX::TXQ_NUM_SAMPLES:
564 case NVPTX::TXQ_NUM_MIPMAP_LEVELS:
565 case NVPTX::SUQ_CHANNEL_ORDER:
566 case NVPTX::SUQ_CHANNEL_DATA_TYPE:
567 case NVPTX::SUQ_WIDTH:
568 case NVPTX::SUQ_HEIGHT:
569 case NVPTX::SUQ_DEPTH:
570 case NVPTX::SUQ_ARRAY_SIZE: {
571 // This is a query, so operand 1 is a surfref/texref
573 lowerImageHandleSymbol(MO.getImm(), MCOp);
582 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
584 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
585 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
586 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
587 const char *Sym = MFI->getImageHandleSymbol(Index);
588 std::string *SymNamePtr =
589 nvTM.getManagedStrPool()->getManagedString(Sym);
590 MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
591 StringRef(SymNamePtr->c_str())));
594 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
595 OutMI.setOpcode(MI->getOpcode());
596 const NVPTXSubtarget &ST = TM.getSubtarget<NVPTXSubtarget>();
598 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
599 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
600 const MachineOperand &MO = MI->getOperand(0);
601 OutMI.addOperand(GetSymbolRef(
602 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
606 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
607 const MachineOperand &MO = MI->getOperand(i);
610 if (!ST.hasImageHandles()) {
611 if (lowerImageHandleOperand(MI, i, MCOp)) {
612 OutMI.addOperand(MCOp);
617 if (lowerOperand(MO, MCOp))
618 OutMI.addOperand(MCOp);
622 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
624 switch (MO.getType()) {
625 default: llvm_unreachable("unknown operand type");
626 case MachineOperand::MO_Register:
627 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
629 case MachineOperand::MO_Immediate:
630 MCOp = MCOperand::CreateImm(MO.getImm());
632 case MachineOperand::MO_MachineBasicBlock:
633 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
634 MO.getMBB()->getSymbol(), OutContext));
636 case MachineOperand::MO_ExternalSymbol:
637 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
639 case MachineOperand::MO_GlobalAddress:
640 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
642 case MachineOperand::MO_FPImmediate: {
643 const ConstantFP *Cnt = MO.getFPImm();
644 APFloat Val = Cnt->getValueAPF();
646 switch (Cnt->getType()->getTypeID()) {
647 default: report_fatal_error("Unsupported FP type"); break;
648 case Type::FloatTyID:
649 MCOp = MCOperand::CreateExpr(
650 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
652 case Type::DoubleTyID:
653 MCOp = MCOperand::CreateExpr(
654 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
663 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
664 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
665 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
667 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
668 unsigned RegNum = RegMap[Reg];
670 // Encode the register class in the upper 4 bits
671 // Must be kept in sync with NVPTXInstPrinter::printRegName
673 if (RC == &NVPTX::Int1RegsRegClass) {
675 } else if (RC == &NVPTX::Int16RegsRegClass) {
677 } else if (RC == &NVPTX::Int32RegsRegClass) {
679 } else if (RC == &NVPTX::Int64RegsRegClass) {
681 } else if (RC == &NVPTX::Float32RegsRegClass) {
683 } else if (RC == &NVPTX::Float64RegsRegClass) {
686 report_fatal_error("Bad register class");
689 // Insert the vreg number
690 Ret |= (RegNum & 0x0FFFFFFF);
693 // Some special-use registers are actually physical registers.
694 // Encode this as the register class ID of 0 and the real register ID.
695 return Reg & 0x0FFFFFFF;
699 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
701 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
703 return MCOperand::CreateExpr(Expr);
706 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
707 const DataLayout *TD = TM.getDataLayout();
708 const TargetLowering *TLI = TM.getTargetLowering();
710 Type *Ty = F->getReturnType();
712 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
714 if (Ty->getTypeID() == Type::VoidTyID)
720 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
722 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
723 size = ITy->getBitWidth();
727 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
728 size = Ty->getPrimitiveSizeInBits();
731 O << ".param .b" << size << " func_retval0";
732 } else if (isa<PointerType>(Ty)) {
733 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
736 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
737 unsigned totalsz = TD->getTypeAllocSize(Ty);
738 unsigned retAlignment = 0;
739 if (!llvm::getAlign(*F, 0, retAlignment))
740 retAlignment = TD->getABITypeAlignment(Ty);
741 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
744 assert(false && "Unknown return type");
747 SmallVector<EVT, 16> vtparts;
748 ComputeValueVTs(*TLI, Ty, vtparts);
750 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
752 EVT elemtype = vtparts[i];
753 if (vtparts[i].isVector()) {
754 elems = vtparts[i].getVectorNumElements();
755 elemtype = vtparts[i].getVectorElementType();
758 for (unsigned j = 0, je = elems; j != je; ++j) {
759 unsigned sz = elemtype.getSizeInBits();
760 if (elemtype.isInteger() && (sz < 32))
762 O << ".reg .b" << sz << " func_retval" << idx;
775 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
777 const Function *F = MF.getFunction();
778 printReturnValStr(F, O);
781 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
782 SmallString<128> Str;
783 raw_svector_ostream O(Str);
785 if (!GlobalsEmitted) {
786 emitGlobals(*MF->getFunction()->getParent());
787 GlobalsEmitted = true;
791 MRI = &MF->getRegInfo();
792 F = MF->getFunction();
793 emitLinkageDirective(F, O);
794 if (llvm::isKernelFunction(*F))
798 printReturnValStr(*MF, O);
803 emitFunctionParamList(*MF, O);
805 if (llvm::isKernelFunction(*F))
806 emitKernelFunctionDirectives(*F, O);
808 OutStreamer.EmitRawText(O.str());
810 prevDebugLoc = DebugLoc();
813 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
815 OutStreamer.EmitRawText(StringRef("{\n"));
816 setAndEmitFunctionVirtualRegisters(*MF);
818 SmallString<128> Str;
819 raw_svector_ostream O(Str);
820 emitDemotedVars(MF->getFunction(), O);
821 OutStreamer.EmitRawText(O.str());
824 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
825 OutStreamer.EmitRawText(StringRef("}\n"));
829 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
830 unsigned RegNo = MI->getOperand(0).getReg();
831 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
832 if (TRI->isVirtualRegister(RegNo)) {
833 OutStreamer.AddComment(Twine("implicit-def: ") +
834 getVirtualRegisterName(RegNo));
836 OutStreamer.AddComment(Twine("implicit-def: ") +
837 TM.getRegisterInfo()->getName(RegNo));
839 OutStreamer.AddBlankLine();
842 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
843 raw_ostream &O) const {
844 // If the NVVM IR has some of reqntid* specified, then output
845 // the reqntid directive, and set the unspecified ones to 1.
846 // If none of reqntid* is specified, don't output reqntid directive.
847 unsigned reqntidx, reqntidy, reqntidz;
848 bool specified = false;
849 if (llvm::getReqNTIDx(F, reqntidx) == false)
853 if (llvm::getReqNTIDy(F, reqntidy) == false)
857 if (llvm::getReqNTIDz(F, reqntidz) == false)
863 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
866 // If the NVVM IR has some of maxntid* specified, then output
867 // the maxntid directive, and set the unspecified ones to 1.
868 // If none of maxntid* is specified, don't output maxntid directive.
869 unsigned maxntidx, maxntidy, maxntidz;
871 if (llvm::getMaxNTIDx(F, maxntidx) == false)
875 if (llvm::getMaxNTIDy(F, maxntidy) == false)
879 if (llvm::getMaxNTIDz(F, maxntidz) == false)
885 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
889 if (llvm::getMinCTASm(F, mincta))
890 O << ".minnctapersm " << mincta << "\n";
894 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
895 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
898 raw_string_ostream NameStr(Name);
900 VRegRCMap::const_iterator I = VRegMapping.find(RC);
901 assert(I != VRegMapping.end() && "Bad register class");
902 const DenseMap<unsigned, unsigned> &RegMap = I->second;
904 VRegMap::const_iterator VI = RegMap.find(Reg);
905 assert(VI != RegMap.end() && "Bad virtual register");
906 unsigned MappedVR = VI->second;
908 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
914 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
916 O << getVirtualRegisterName(vr);
919 void NVPTXAsmPrinter::printVecModifiedImmediate(
920 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
921 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
922 int Imm = (int) MO.getImm();
923 if (0 == strcmp(Modifier, "vecelem"))
924 O << "_" << vecelem[Imm];
925 else if (0 == strcmp(Modifier, "vecv4comm1")) {
926 if ((Imm < 0) || (Imm > 3))
928 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
929 if ((Imm < 4) || (Imm > 7))
931 } else if (0 == strcmp(Modifier, "vecv4pos")) {
934 O << "_" << vecelem[Imm % 4];
935 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
936 if ((Imm < 0) || (Imm > 1))
938 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
939 if ((Imm < 2) || (Imm > 3))
941 } else if (0 == strcmp(Modifier, "vecv2pos")) {
944 O << "_" << vecelem[Imm % 2];
946 llvm_unreachable("Unknown Modifier on immediate operand");
951 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
953 emitLinkageDirective(F, O);
954 if (llvm::isKernelFunction(*F))
958 printReturnValStr(F, O);
959 O << *getSymbol(F) << "\n";
960 emitFunctionParamList(F, O);
964 static bool usedInGlobalVarDef(const Constant *C) {
968 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
969 if (GV->getName().str() == "llvm.used")
974 for (const User *U : C->users())
975 if (const Constant *C = dyn_cast<Constant>(U))
976 if (usedInGlobalVarDef(C))
982 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
983 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
984 if (othergv->getName().str() == "llvm.used")
988 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
989 if (instr->getParent() && instr->getParent()->getParent()) {
990 const Function *curFunc = instr->getParent()->getParent();
991 if (oneFunc && (curFunc != oneFunc))
999 if (const MDNode *md = dyn_cast<MDNode>(U))
1000 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
1001 (md->getName().str() == "llvm.dbg.sp")))
1004 for (const User *UU : U->users())
1005 if (usedInOneFunc(UU, oneFunc) == false)
1011 /* Find out if a global variable can be demoted to local scope.
1012 * Currently, this is valid for CUDA shared variables, which have local
1013 * scope and global lifetime. So the conditions to check are :
1014 * 1. Is the global variable in shared address space?
1015 * 2. Does it have internal linkage?
1016 * 3. Is the global variable referenced only in one function?
1018 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
1019 if (gv->hasInternalLinkage() == false)
1021 const PointerType *Pty = gv->getType();
1022 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
1025 const Function *oneFunc = nullptr;
1027 bool flag = usedInOneFunc(gv, oneFunc);
1036 static bool useFuncSeen(const Constant *C,
1037 llvm::DenseMap<const Function *, bool> &seenMap) {
1038 for (const User *U : C->users()) {
1039 if (const Constant *cu = dyn_cast<Constant>(U)) {
1040 if (useFuncSeen(cu, seenMap))
1042 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
1043 const BasicBlock *bb = I->getParent();
1046 const Function *caller = bb->getParent();
1049 if (seenMap.find(caller) != seenMap.end())
1056 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
1057 llvm::DenseMap<const Function *, bool> seenMap;
1058 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
1059 const Function *F = FI;
1061 if (F->isDeclaration()) {
1064 if (F->getIntrinsicID())
1066 emitDeclaration(F, O);
1069 for (const User *U : F->users()) {
1070 if (const Constant *C = dyn_cast<Constant>(U)) {
1071 if (usedInGlobalVarDef(C)) {
1072 // The use is in the initialization of a global variable
1073 // that is a function pointer, so print a declaration
1074 // for the original function
1075 emitDeclaration(F, O);
1078 // Emit a declaration of this function if the function that
1079 // uses this constant expr has already been seen.
1080 if (useFuncSeen(C, seenMap)) {
1081 emitDeclaration(F, O);
1086 if (!isa<Instruction>(U))
1088 const Instruction *instr = cast<Instruction>(U);
1089 const BasicBlock *bb = instr->getParent();
1092 const Function *caller = bb->getParent();
1096 // If a caller has already been seen, then the caller is
1097 // appearing in the module before the callee. so print out
1098 // a declaration for the callee.
1099 if (seenMap.find(caller) != seenMap.end()) {
1100 emitDeclaration(F, O);
1108 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
1109 DebugInfoFinder DbgFinder;
1110 DbgFinder.processModule(M);
1113 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
1114 StringRef Filename(DIUnit.getFilename());
1115 StringRef Dirname(DIUnit.getDirectory());
1116 SmallString<128> FullPathName = Dirname;
1117 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
1118 sys::path::append(FullPathName, Filename);
1119 Filename = FullPathName.str();
1121 if (filenameMap.find(Filename.str()) != filenameMap.end())
1123 filenameMap[Filename.str()] = i;
1124 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
1128 for (DISubprogram SP : DbgFinder.subprograms()) {
1129 StringRef Filename(SP.getFilename());
1130 StringRef Dirname(SP.getDirectory());
1131 SmallString<128> FullPathName = Dirname;
1132 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
1133 sys::path::append(FullPathName, Filename);
1134 Filename = FullPathName.str();
1136 if (filenameMap.find(Filename.str()) != filenameMap.end())
1138 filenameMap[Filename.str()] = i;
1143 bool NVPTXAsmPrinter::doInitialization(Module &M) {
1145 SmallString<128> Str1;
1146 raw_svector_ostream OS1(Str1);
1148 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
1149 MMI->AnalyzeModule(M);
1151 // We need to call the parent's one explicitly.
1152 //bool Result = AsmPrinter::doInitialization(M);
1154 // Initialize TargetLoweringObjectFile.
1155 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
1156 .Initialize(OutContext, TM);
1158 Mang = new Mangler(TM.getDataLayout());
1160 // Emit header before any dwarf directives are emitted below.
1162 OutStreamer.EmitRawText(OS1.str());
1164 // Already commented out
1165 //bool Result = AsmPrinter::doInitialization(M);
1167 // Emit module-level inline asm if it exists.
1168 if (!M.getModuleInlineAsm().empty()) {
1169 OutStreamer.AddComment("Start of file scope inline assembly");
1170 OutStreamer.AddBlankLine();
1171 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
1172 OutStreamer.AddBlankLine();
1173 OutStreamer.AddComment("End of file scope inline assembly");
1174 OutStreamer.AddBlankLine();
1177 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
1178 recordAndEmitFilenames(M);
1180 GlobalsEmitted = false;
1182 return false; // success
1185 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
1186 SmallString<128> Str2;
1187 raw_svector_ostream OS2(Str2);
1189 emitDeclarations(M, OS2);
1191 // As ptxas does not support forward references of globals, we need to first
1192 // sort the list of module-level globals in def-use order. We visit each
1193 // global variable in order, and ensure that we emit it *after* its dependent
1194 // globals. We use a little extra memory maintaining both a set and a list to
1195 // have fast searches while maintaining a strict ordering.
1196 SmallVector<const GlobalVariable *, 8> Globals;
1197 DenseSet<const GlobalVariable *> GVVisited;
1198 DenseSet<const GlobalVariable *> GVVisiting;
1200 // Visit each global variable, in order
1201 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1203 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
1205 assert(GVVisited.size() == M.getGlobalList().size() &&
1206 "Missed a global variable");
1207 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
1209 // Print out module-level global variables in proper order
1210 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1211 printModuleLevelGV(Globals[i], OS2);
1215 OutStreamer.EmitRawText(OS2.str());
1218 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
1220 O << "// Generated by LLVM NVPTX Back-End\n";
1224 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
1225 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
1228 O << nvptxSubtarget.getTargetName();
1230 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
1231 O << ", texmode_independent";
1232 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1233 if (!nvptxSubtarget.hasDouble())
1234 O << ", map_f64_to_f32";
1237 if (MAI->doesSupportDebugInformation())
1242 O << ".address_size ";
1243 if (nvptxSubtarget.is64Bit())
1252 bool NVPTXAsmPrinter::doFinalization(Module &M) {
1254 // If we did not emit any functions, then the global declarations have not
1255 // yet been emitted.
1256 if (!GlobalsEmitted) {
1258 GlobalsEmitted = true;
1261 // XXX Temproarily remove global variables so that doFinalization() will not
1262 // emit them again (global variables are emitted at beginning).
1264 Module::GlobalListType &global_list = M.getGlobalList();
1265 int i, n = global_list.size();
1266 GlobalVariable **gv_array = new GlobalVariable *[n];
1268 // first, back-up GlobalVariable in gv_array
1270 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1272 gv_array[i++] = &*I;
1274 // second, empty global_list
1275 while (!global_list.empty())
1276 global_list.remove(global_list.begin());
1278 // call doFinalization
1279 bool ret = AsmPrinter::doFinalization(M);
1281 // now we restore global variables
1282 for (i = 0; i < n; i++)
1283 global_list.insert(global_list.end(), gv_array[i]);
1285 clearAnnotationCache(&M);
1290 //bool Result = AsmPrinter::doFinalization(M);
1291 // Instead of calling the parents doFinalization, we may
1292 // clone parents doFinalization and customize here.
1293 // Currently, we if NVISA out the EmitGlobals() in
1294 // parent's doFinalization, which is too intrusive.
1296 // Same for the doInitialization.
1300 // This function emits appropriate linkage directives for
1301 // functions and global variables.
1303 // extern function declaration -> .extern
1304 // extern function definition -> .visible
1305 // external global variable with init -> .visible
1306 // external without init -> .extern
1307 // appending -> not allowed, assert.
1309 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1311 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1312 if (V->hasExternalLinkage()) {
1313 if (isa<GlobalVariable>(V)) {
1314 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1316 if (GVar->hasInitializer())
1321 } else if (V->isDeclaration())
1325 } else if (V->hasAppendingLinkage()) {
1327 msg.append("Error: ");
1328 msg.append("Symbol ");
1330 msg.append(V->getName().str());
1331 msg.append("has unsupported appending linkage type");
1332 llvm_unreachable(msg.c_str());
1337 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1339 bool processDemoted) {
1342 if (GVar->hasSection()) {
1343 if (GVar->getSection() == StringRef("llvm.metadata"))
1347 const DataLayout *TD = TM.getDataLayout();
1349 // GlobalVariables are always constant pointers themselves.
1350 const PointerType *PTy = GVar->getType();
1351 Type *ETy = PTy->getElementType();
1353 if (GVar->hasExternalLinkage()) {
1354 if (GVar->hasInitializer())
1360 if (llvm::isTexture(*GVar)) {
1361 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1365 if (llvm::isSurface(*GVar)) {
1366 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1370 if (GVar->isDeclaration()) {
1371 // (extern) declarations, no definition or initializer
1372 // Currently the only known declaration is for an automatic __local
1373 // (.shared) promoted to global.
1374 emitPTXGlobalVariable(GVar, O);
1379 if (llvm::isSampler(*GVar)) {
1380 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1382 const Constant *Initializer = nullptr;
1383 if (GVar->hasInitializer())
1384 Initializer = GVar->getInitializer();
1385 const ConstantInt *CI = nullptr;
1387 CI = dyn_cast<ConstantInt>(Initializer);
1389 unsigned sample = CI->getZExtValue();
1394 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1396 O << "addr_mode_" << i << " = ";
1402 O << "clamp_to_border";
1405 O << "clamp_to_edge";
1416 O << "filter_mode = ";
1417 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1425 llvm_unreachable("Anisotropic filtering is not supported");
1430 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1431 O << ", force_unnormalized_coords = 1";
1440 if (GVar->hasPrivateLinkage()) {
1442 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1445 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1446 if (!strncmp(GVar->getName().data(), "filename", 8))
1448 if (GVar->use_empty())
1452 const Function *demotedFunc = nullptr;
1453 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1454 O << "// " << GVar->getName().str() << " has been demoted\n";
1455 if (localDecls.find(demotedFunc) != localDecls.end())
1456 localDecls[demotedFunc].push_back(GVar);
1458 std::vector<const GlobalVariable *> temp;
1459 temp.push_back(GVar);
1460 localDecls[demotedFunc] = temp;
1466 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1467 if (GVar->getAlignment() == 0)
1468 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1470 O << " .align " << GVar->getAlignment();
1472 if (ETy->isSingleValueType()) {
1474 // Special case: ABI requires that we use .u8 for predicates
1475 if (ETy->isIntegerTy(1))
1478 O << getPTXFundamentalTypeStr(ETy, false);
1480 O << *getSymbol(GVar);
1482 // Ptx allows variable initilization only for constant and global state
1484 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1485 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1486 GVar->hasInitializer()) {
1487 const Constant *Initializer = GVar->getInitializer();
1488 if (!Initializer->isNullValue()) {
1490 printScalarConstant(Initializer, O);
1494 unsigned int ElementSize = 0;
1496 // Although PTX has direct support for struct type and array type and
1497 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1498 // targets that support these high level field accesses. Structs, arrays
1499 // and vectors are lowered into arrays of bytes.
1500 switch (ETy->getTypeID()) {
1501 case Type::StructTyID:
1502 case Type::ArrayTyID:
1503 case Type::VectorTyID:
1504 ElementSize = TD->getTypeStoreSize(ETy);
1505 // Ptx allows variable initilization only for constant and
1506 // global state spaces.
1507 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1508 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1509 GVar->hasInitializer()) {
1510 const Constant *Initializer = GVar->getInitializer();
1511 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1512 AggBuffer aggBuffer(ElementSize, O, *this);
1513 bufferAggregateConstant(Initializer, &aggBuffer);
1514 if (aggBuffer.numSymbols) {
1515 if (nvptxSubtarget.is64Bit()) {
1516 O << " .u64 " << *getSymbol(GVar) << "[";
1517 O << ElementSize / 8;
1519 O << " .u32 " << *getSymbol(GVar) << "[";
1520 O << ElementSize / 4;
1524 O << " .b8 " << *getSymbol(GVar) << "[";
1532 O << " .b8 " << *getSymbol(GVar);
1540 O << " .b8 " << *getSymbol(GVar);
1549 llvm_unreachable("type not supported yet");
1556 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1557 if (localDecls.find(f) == localDecls.end())
1560 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1562 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1563 O << "\t// demoted variable\n\t";
1564 printModuleLevelGV(gvars[i], O, true);
1568 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1569 raw_ostream &O) const {
1570 switch (AddressSpace) {
1571 case llvm::ADDRESS_SPACE_LOCAL:
1574 case llvm::ADDRESS_SPACE_GLOBAL:
1577 case llvm::ADDRESS_SPACE_CONST:
1580 case llvm::ADDRESS_SPACE_SHARED:
1584 report_fatal_error("Bad address space found while emitting PTX");
1590 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1591 switch (Ty->getTypeID()) {
1593 llvm_unreachable("unexpected type");
1595 case Type::IntegerTyID: {
1596 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1599 else if (NumBits <= 64) {
1600 std::string name = "u";
1601 return name + utostr(NumBits);
1603 llvm_unreachable("Integer too large");
1608 case Type::FloatTyID:
1610 case Type::DoubleTyID:
1612 case Type::PointerTyID:
1613 if (nvptxSubtarget.is64Bit())
1623 llvm_unreachable("unexpected type");
1627 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1630 const DataLayout *TD = TM.getDataLayout();
1632 // GlobalVariables are always constant pointers themselves.
1633 const PointerType *PTy = GVar->getType();
1634 Type *ETy = PTy->getElementType();
1637 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1638 if (GVar->getAlignment() == 0)
1639 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1641 O << " .align " << GVar->getAlignment();
1643 if (ETy->isSingleValueType()) {
1645 O << getPTXFundamentalTypeStr(ETy);
1647 O << *getSymbol(GVar);
1651 int64_t ElementSize = 0;
1653 // Although PTX has direct support for struct type and array type and LLVM IR
1654 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1655 // support these high level field accesses. Structs and arrays are lowered
1656 // into arrays of bytes.
1657 switch (ETy->getTypeID()) {
1658 case Type::StructTyID:
1659 case Type::ArrayTyID:
1660 case Type::VectorTyID:
1661 ElementSize = TD->getTypeStoreSize(ETy);
1662 O << " .b8 " << *getSymbol(GVar) << "[";
1664 O << itostr(ElementSize);
1669 llvm_unreachable("type not supported yet");
1674 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1675 if (Ty->isSingleValueType())
1676 return TD->getPrefTypeAlignment(Ty);
1678 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1680 return getOpenCLAlignment(TD, ATy->getElementType());
1682 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1684 Type *ETy = VTy->getElementType();
1685 unsigned int numE = VTy->getNumElements();
1686 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1690 return numE * alignE;
1693 const StructType *STy = dyn_cast<StructType>(Ty);
1695 unsigned int alignStruct = 1;
1696 // Go through each element of the struct and find the
1697 // largest alignment.
1698 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1699 Type *ETy = STy->getElementType(i);
1700 unsigned int align = getOpenCLAlignment(TD, ETy);
1701 if (align > alignStruct)
1702 alignStruct = align;
1707 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1709 return TD->getPointerPrefAlignment();
1710 return TD->getPrefTypeAlignment(Ty);
1713 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1714 int paramIndex, raw_ostream &O) {
1715 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1716 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1717 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1719 std::string argName = I->getName();
1720 const char *p = argName.c_str();
1731 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1732 Function::const_arg_iterator I, E;
1735 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1736 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1737 O << *CurrentFnSym << "_param_" << paramIndex;
1741 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1742 if (i == paramIndex) {
1743 printParamName(I, paramIndex, O);
1747 llvm_unreachable("paramIndex out of bound");
1750 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1751 const DataLayout *TD = TM.getDataLayout();
1752 const AttributeSet &PAL = F->getAttributes();
1753 const TargetLowering *TLI = TM.getTargetLowering();
1754 Function::const_arg_iterator I, E;
1755 unsigned paramIndex = 0;
1757 bool isKernelFunc = llvm::isKernelFunction(*F);
1758 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1759 MVT thePointerTy = TLI->getPointerTy();
1763 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1764 Type *Ty = I->getType();
1771 // Handle image/sampler parameters
1772 if (isKernelFunction(*F)) {
1773 if (isSampler(*I) || isImage(*I)) {
1775 std::string sname = I->getName();
1776 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1777 if (nvptxSubtarget.hasImageHandles())
1778 O << "\t.param .u64 .ptr .surfref ";
1780 O << "\t.param .surfref ";
1781 O << *CurrentFnSym << "_param_" << paramIndex;
1783 else { // Default image is read_only
1784 if (nvptxSubtarget.hasImageHandles())
1785 O << "\t.param .u64 .ptr .texref ";
1787 O << "\t.param .texref ";
1788 O << *CurrentFnSym << "_param_" << paramIndex;
1791 if (nvptxSubtarget.hasImageHandles())
1792 O << "\t.param .u64 .ptr .samplerref ";
1794 O << "\t.param .samplerref ";
1795 O << *CurrentFnSym << "_param_" << paramIndex;
1801 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1802 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1803 // Just print .param .align <a> .b8 .param[size];
1804 // <a> = PAL.getparamalignment
1805 // size = typeallocsize of element type
1806 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1808 align = TD->getABITypeAlignment(Ty);
1810 unsigned sz = TD->getTypeAllocSize(Ty);
1811 O << "\t.param .align " << align << " .b8 ";
1812 printParamName(I, paramIndex, O);
1813 O << "[" << sz << "]";
1818 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1821 // Special handling for pointer arguments to kernel
1822 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1824 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1825 Type *ETy = PTy->getElementType();
1826 int addrSpace = PTy->getAddressSpace();
1827 switch (addrSpace) {
1831 case llvm::ADDRESS_SPACE_CONST:
1832 O << ".ptr .const ";
1834 case llvm::ADDRESS_SPACE_SHARED:
1835 O << ".ptr .shared ";
1837 case llvm::ADDRESS_SPACE_GLOBAL:
1838 O << ".ptr .global ";
1841 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1843 printParamName(I, paramIndex, O);
1847 // non-pointer scalar to kernel func
1849 // Special case: predicate operands become .u8 types
1850 if (Ty->isIntegerTy(1))
1853 O << getPTXFundamentalTypeStr(Ty);
1855 printParamName(I, paramIndex, O);
1858 // Non-kernel function, just print .param .b<size> for ABI
1859 // and .reg .b<size> for non-ABI
1861 if (isa<IntegerType>(Ty)) {
1862 sz = cast<IntegerType>(Ty)->getBitWidth();
1865 } else if (isa<PointerType>(Ty))
1866 sz = thePointerTy.getSizeInBits();
1868 sz = Ty->getPrimitiveSizeInBits();
1870 O << "\t.param .b" << sz << " ";
1872 O << "\t.reg .b" << sz << " ";
1873 printParamName(I, paramIndex, O);
1877 // param has byVal attribute. So should be a pointer
1878 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1879 assert(PTy && "Param with byval attribute should be a pointer type");
1880 Type *ETy = PTy->getElementType();
1882 if (isABI || isKernelFunc) {
1883 // Just print .param .align <a> .b8 .param[size];
1884 // <a> = PAL.getparamalignment
1885 // size = typeallocsize of element type
1886 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1888 align = TD->getABITypeAlignment(ETy);
1890 unsigned sz = TD->getTypeAllocSize(ETy);
1891 O << "\t.param .align " << align << " .b8 ";
1892 printParamName(I, paramIndex, O);
1893 O << "[" << sz << "]";
1896 // Split the ETy into constituent parts and
1897 // print .param .b<size> <name> for each part.
1898 // Further, if a part is vector, print the above for
1899 // each vector element.
1900 SmallVector<EVT, 16> vtparts;
1901 ComputeValueVTs(*TLI, ETy, vtparts);
1902 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1904 EVT elemtype = vtparts[i];
1905 if (vtparts[i].isVector()) {
1906 elems = vtparts[i].getVectorNumElements();
1907 elemtype = vtparts[i].getVectorElementType();
1910 for (unsigned j = 0, je = elems; j != je; ++j) {
1911 unsigned sz = elemtype.getSizeInBits();
1912 if (elemtype.isInteger() && (sz < 32))
1914 O << "\t.reg .b" << sz << " ";
1915 printParamName(I, paramIndex, O);
1931 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1933 const Function *F = MF.getFunction();
1934 emitFunctionParamList(F, O);
1937 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1938 const MachineFunction &MF) {
1939 SmallString<128> Str;
1940 raw_svector_ostream O(Str);
1942 // Map the global virtual register number to a register class specific
1943 // virtual register number starting from 1 with that class.
1944 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1945 //unsigned numRegClasses = TRI->getNumRegClasses();
1947 // Emit the Fake Stack Object
1948 const MachineFrameInfo *MFI = MF.getFrameInfo();
1949 int NumBytes = (int) MFI->getStackSize();
1951 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1952 << getFunctionNumber() << "[" << NumBytes << "];\n";
1953 if (nvptxSubtarget.is64Bit()) {
1954 O << "\t.reg .b64 \t%SP;\n";
1955 O << "\t.reg .b64 \t%SPL;\n";
1957 O << "\t.reg .b32 \t%SP;\n";
1958 O << "\t.reg .b32 \t%SPL;\n";
1962 // Go through all virtual registers to establish the mapping between the
1964 // register number and the per class virtual register number.
1965 // We use the per class virtual register number in the ptx output.
1966 unsigned int numVRs = MRI->getNumVirtRegs();
1967 for (unsigned i = 0; i < numVRs; i++) {
1968 unsigned int vr = TRI->index2VirtReg(i);
1969 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1970 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1971 int n = regmap.size();
1972 regmap.insert(std::make_pair(vr, n + 1));
1975 // Emit register declarations
1976 // @TODO: Extract out the real register usage
1977 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1978 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1979 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1980 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1981 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1982 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1983 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1985 // Emit declaration of the virtual registers or 'physical' registers for
1986 // each register class
1987 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1988 const TargetRegisterClass *RC = TRI->getRegClass(i);
1989 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1990 std::string rcname = getNVPTXRegClassName(RC);
1991 std::string rcStr = getNVPTXRegClassStr(RC);
1992 int n = regmap.size();
1994 // Only declare those registers that may be used.
1996 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
2001 OutStreamer.EmitRawText(O.str());
2004 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
2005 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
2007 unsigned int numHex;
2010 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
2013 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
2014 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
2017 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
2019 llvm_unreachable("unsupported fp type");
2021 APInt API = APF.bitcastToAPInt();
2022 std::string hexstr(utohexstr(API.getZExtValue()));
2024 if (hexstr.length() < numHex)
2025 O << std::string(numHex - hexstr.length(), '0');
2026 O << utohexstr(API.getZExtValue());
2029 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
2030 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
2031 O << CI->getValue();
2034 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
2035 printFPConstant(CFP, O);
2038 if (isa<ConstantPointerNull>(CPV)) {
2042 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
2043 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
2044 bool IsNonGenericPointer = false;
2045 if (PTy && PTy->getAddressSpace() != 0) {
2046 IsNonGenericPointer = true;
2048 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
2050 O << *getSymbol(GVar);
2053 O << *getSymbol(GVar);
2057 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2058 const Value *v = Cexpr->stripPointerCasts();
2059 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
2060 bool IsNonGenericPointer = false;
2061 if (PTy && PTy->getAddressSpace() != 0) {
2062 IsNonGenericPointer = true;
2064 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
2065 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
2067 O << *getSymbol(GVar);
2070 O << *getSymbol(GVar);
2074 O << *LowerConstant(CPV, *this);
2078 llvm_unreachable("Not scalar type found in printScalarConstant()");
2081 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
2082 AggBuffer *aggBuffer) {
2084 const DataLayout *TD = TM.getDataLayout();
2086 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
2087 int s = TD->getTypeAllocSize(CPV->getType());
2090 aggBuffer->addZeros(s);
2095 switch (CPV->getType()->getTypeID()) {
2097 case Type::IntegerTyID: {
2098 const Type *ETy = CPV->getType();
2099 if (ETy == Type::getInt8Ty(CPV->getContext())) {
2101 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
2103 aggBuffer->addBytes(ptr, 1, Bytes);
2104 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
2105 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
2106 ptr = (unsigned char *)&int16;
2107 aggBuffer->addBytes(ptr, 2, Bytes);
2108 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
2109 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
2110 int int32 = (int)(constInt->getZExtValue());
2111 ptr = (unsigned char *)&int32;
2112 aggBuffer->addBytes(ptr, 4, Bytes);
2114 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2115 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
2116 ConstantFoldConstantExpression(Cexpr, TD))) {
2117 int int32 = (int)(constInt->getZExtValue());
2118 ptr = (unsigned char *)&int32;
2119 aggBuffer->addBytes(ptr, 4, Bytes);
2122 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
2123 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
2124 aggBuffer->addSymbol(v);
2125 aggBuffer->addZeros(4);
2129 llvm_unreachable("unsupported integer const type");
2130 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
2131 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
2132 long long int64 = (long long)(constInt->getZExtValue());
2133 ptr = (unsigned char *)&int64;
2134 aggBuffer->addBytes(ptr, 8, Bytes);
2136 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2137 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
2138 ConstantFoldConstantExpression(Cexpr, TD))) {
2139 long long int64 = (long long)(constInt->getZExtValue());
2140 ptr = (unsigned char *)&int64;
2141 aggBuffer->addBytes(ptr, 8, Bytes);
2144 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
2145 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
2146 aggBuffer->addSymbol(v);
2147 aggBuffer->addZeros(8);
2151 llvm_unreachable("unsupported integer const type");
2153 llvm_unreachable("unsupported integer const type");
2156 case Type::FloatTyID:
2157 case Type::DoubleTyID: {
2158 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
2159 const Type *Ty = CFP->getType();
2160 if (Ty == Type::getFloatTy(CPV->getContext())) {
2161 float float32 = (float) CFP->getValueAPF().convertToFloat();
2162 ptr = (unsigned char *)&float32;
2163 aggBuffer->addBytes(ptr, 4, Bytes);
2164 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
2165 double float64 = CFP->getValueAPF().convertToDouble();
2166 ptr = (unsigned char *)&float64;
2167 aggBuffer->addBytes(ptr, 8, Bytes);
2169 llvm_unreachable("unsupported fp const type");
2173 case Type::PointerTyID: {
2174 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
2175 aggBuffer->addSymbol(GVar);
2176 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2177 const Value *v = Cexpr->stripPointerCasts();
2178 aggBuffer->addSymbol(v);
2180 unsigned int s = TD->getTypeAllocSize(CPV->getType());
2181 aggBuffer->addZeros(s);
2185 case Type::ArrayTyID:
2186 case Type::VectorTyID:
2187 case Type::StructTyID: {
2188 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
2189 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
2190 int ElementSize = TD->getTypeAllocSize(CPV->getType());
2191 bufferAggregateConstant(CPV, aggBuffer);
2192 if (Bytes > ElementSize)
2193 aggBuffer->addZeros(Bytes - ElementSize);
2194 } else if (isa<ConstantAggregateZero>(CPV))
2195 aggBuffer->addZeros(Bytes);
2197 llvm_unreachable("Unexpected Constant type");
2202 llvm_unreachable("unsupported type");
2206 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
2207 AggBuffer *aggBuffer) {
2208 const DataLayout *TD = TM.getDataLayout();
2212 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
2213 if (CPV->getNumOperands())
2214 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
2215 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
2219 if (const ConstantDataSequential *CDS =
2220 dyn_cast<ConstantDataSequential>(CPV)) {
2221 if (CDS->getNumElements())
2222 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
2223 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
2228 if (isa<ConstantStruct>(CPV)) {
2229 if (CPV->getNumOperands()) {
2230 StructType *ST = cast<StructType>(CPV->getType());
2231 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
2233 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
2234 TD->getTypeAllocSize(ST) -
2235 TD->getStructLayout(ST)->getElementOffset(i);
2237 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
2238 TD->getStructLayout(ST)->getElementOffset(i);
2239 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
2244 llvm_unreachable("unsupported constant type in printAggregateConstant()");
2247 // buildTypeNameMap - Run through symbol table looking for type names.
2250 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
2252 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
2254 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
2255 !PI->second.compare("struct._image2d_t") ||
2256 !PI->second.compare("struct._image3d_t")))
2263 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2264 switch (MI.getOpcode()) {
2267 case NVPTX::CallArgBeginInst:
2268 case NVPTX::CallArgEndInst0:
2269 case NVPTX::CallArgEndInst1:
2270 case NVPTX::CallArgF32:
2271 case NVPTX::CallArgF64:
2272 case NVPTX::CallArgI16:
2273 case NVPTX::CallArgI32:
2274 case NVPTX::CallArgI32imm:
2275 case NVPTX::CallArgI64:
2276 case NVPTX::CallArgParam:
2277 case NVPTX::CallVoidInst:
2278 case NVPTX::CallVoidInstReg:
2279 case NVPTX::Callseq_End:
2280 case NVPTX::CallVoidInstReg64:
2281 case NVPTX::DeclareParamInst:
2282 case NVPTX::DeclareRetMemInst:
2283 case NVPTX::DeclareRetRegInst:
2284 case NVPTX::DeclareRetScalarInst:
2285 case NVPTX::DeclareScalarParamInst:
2286 case NVPTX::DeclareScalarRegInst:
2287 case NVPTX::StoreParamF32:
2288 case NVPTX::StoreParamF64:
2289 case NVPTX::StoreParamI16:
2290 case NVPTX::StoreParamI32:
2291 case NVPTX::StoreParamI64:
2292 case NVPTX::StoreParamI8:
2293 case NVPTX::StoreRetvalF32:
2294 case NVPTX::StoreRetvalF64:
2295 case NVPTX::StoreRetvalI16:
2296 case NVPTX::StoreRetvalI32:
2297 case NVPTX::StoreRetvalI64:
2298 case NVPTX::StoreRetvalI8:
2299 case NVPTX::LastCallArgF32:
2300 case NVPTX::LastCallArgF64:
2301 case NVPTX::LastCallArgI16:
2302 case NVPTX::LastCallArgI32:
2303 case NVPTX::LastCallArgI32imm:
2304 case NVPTX::LastCallArgI64:
2305 case NVPTX::LastCallArgParam:
2306 case NVPTX::LoadParamMemF32:
2307 case NVPTX::LoadParamMemF64:
2308 case NVPTX::LoadParamMemI16:
2309 case NVPTX::LoadParamMemI32:
2310 case NVPTX::LoadParamMemI64:
2311 case NVPTX::LoadParamMemI8:
2312 case NVPTX::PrototypeInst:
2313 case NVPTX::DBG_VALUE:
2319 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2321 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2322 unsigned AsmVariant,
2323 const char *ExtraCode, raw_ostream &O) {
2324 if (ExtraCode && ExtraCode[0]) {
2325 if (ExtraCode[1] != 0)
2326 return true; // Unknown modifier.
2328 switch (ExtraCode[0]) {
2330 // See if this is a generic print operand
2331 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2337 printOperand(MI, OpNo, O);
2342 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2343 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2344 const char *ExtraCode, raw_ostream &O) {
2345 if (ExtraCode && ExtraCode[0])
2346 return true; // Unknown modifier
2349 printMemOperand(MI, OpNo, O);
2355 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2356 raw_ostream &O, const char *Modifier) {
2357 const MachineOperand &MO = MI->getOperand(opNum);
2358 switch (MO.getType()) {
2359 case MachineOperand::MO_Register:
2360 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2361 if (MO.getReg() == NVPTX::VRDepot)
2362 O << DEPOTNAME << getFunctionNumber();
2364 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2366 emitVirtualRegister(MO.getReg(), O);
2370 case MachineOperand::MO_Immediate:
2373 else if (strstr(Modifier, "vec") == Modifier)
2374 printVecModifiedImmediate(MO, Modifier, O);
2377 "Don't know how to handle modifier on immediate operand");
2380 case MachineOperand::MO_FPImmediate:
2381 printFPConstant(MO.getFPImm(), O);
2384 case MachineOperand::MO_GlobalAddress:
2385 O << *getSymbol(MO.getGlobal());
2388 case MachineOperand::MO_MachineBasicBlock:
2389 O << *MO.getMBB()->getSymbol();
2393 llvm_unreachable("Operand type not supported.");
2397 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2398 raw_ostream &O, const char *Modifier) {
2399 printOperand(MI, opNum, O);
2401 if (Modifier && !strcmp(Modifier, "add")) {
2403 printOperand(MI, opNum + 1, O);
2405 if (MI->getOperand(opNum + 1).isImm() &&
2406 MI->getOperand(opNum + 1).getImm() == 0)
2407 return; // don't print ',0' or '+0'
2409 printOperand(MI, opNum + 1, O);
2414 // Force static initialization.
2415 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2416 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2417 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2420 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2421 std::stringstream temp;
2422 LineReader *reader = this->getReader(filename.str());
2424 temp << filename.str();
2428 temp << reader->readLine(line);
2430 this->OutStreamer.EmitRawText(Twine(temp.str()));
2433 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2435 reader = new LineReader(filename);
2438 if (reader->fileName() != filename) {
2440 reader = new LineReader(filename);
2446 std::string LineReader::readLine(unsigned lineNum) {
2447 if (lineNum < theCurLine) {
2449 fstr.seekg(0, std::ios::beg);
2451 while (theCurLine < lineNum) {
2452 fstr.getline(buff, 500);
2458 // Force static initialization.
2459 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2460 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2461 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);