1 //===-- "main" function of libc-wrappergen --------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "utils/LibcTableGenUtil/APIIndexer.h"
10 
11 #include "llvm/ADT/StringRef.h"
12 #include "llvm/Support/CommandLine.h"
13 #include "llvm/Support/MemoryBuffer.h"
14 #include "llvm/TableGen/Error.h"
15 #include "llvm/TableGen/Main.h"
16 
17 #include <sstream>
18 #include <string>
19 
20 llvm::cl::opt<std::string>
21     FunctionName("name", llvm::cl::desc("Name of the function to be wrapped."),
22                  llvm::cl::value_desc("<function name>"), llvm::cl::Required);
23 llvm::cl::opt<std::string>
24     AliaseeString("aliasee",
25                   llvm::cl::desc("Declare as an alias to this C name."),
26                   llvm::cl::value_desc("<aliasee string>"));
27 llvm::cl::opt<std::string>
28     AliaseeFile("aliasee-file",
29                 llvm::cl::desc("Declare as an alias to the C name read from "
30                                "this file."),
31                 llvm::cl::value_desc("<path to a file containing alias name>"));
32 llvm::cl::opt<std::string>
33     AppendToFile("append-to-file",
34                  llvm::cl::desc("Append the generated content at the end of "
35                                 "the contents of this file."),
36                  llvm::cl::value_desc("<path to a file>"));
37 
38 static std::string GetAliaseeName() {
39   if (AliaseeString.size() > 0)
40     return AliaseeString;
41 
42   auto ErrorOrBuf = llvm::MemoryBuffer::getFile(AliaseeFile);
43   if (!ErrorOrBuf)
44     llvm::PrintFatalError("Unable to read the aliasee file " + AliaseeFile);
45   return std::string(ErrorOrBuf.get()->getBuffer().trim());
46 }
47 
48 static bool WrapperGenMain(llvm::raw_ostream &OS, llvm::RecordKeeper &Records) {
49   if (!AliaseeString.empty() && !AliaseeFile.empty()) {
50     llvm::PrintFatalError("The options 'aliasee' and 'aliasee-file' cannot "
51                           "be specified simultaniously.");
52   }
53 
54   llvm_libc::APIIndexer Indexer(Records);
55   auto Iter = Indexer.FunctionSpecMap.find(FunctionName);
56   if (Iter == Indexer.FunctionSpecMap.end()) {
57     llvm::PrintFatalError("Function '" + FunctionName +
58                           "' not found in any standard spec.");
59   }
60 
61   bool EmitAlias = !(AliaseeString.empty() && AliaseeFile.empty());
62 
63   if (!EmitAlias && AppendToFile.empty()) {
64     // If not emitting an alias, and not appending to another file,
65     // we should include the implementation header to ensure the wrapper
66     // compiles.
67     // To avoid all confusion, we include the implementation header using the
68     // full path (relative to the libc directory.)
69     std::string Header = Indexer.FunctionToHeaderMap[FunctionName];
70     auto RelPath =
71         llvm::StringRef(Header).drop_back(2); // Drop the ".h" suffix.
72     OS << "#include \"src/" << RelPath << "/" << FunctionName << ".h\"\n";
73   }
74   if (!AppendToFile.empty()) {
75     auto ErrorOrBuf = llvm::MemoryBuffer::getFile(AppendToFile);
76     if (!ErrorOrBuf) {
77       llvm::PrintFatalError("Unable to read the file '" + AppendToFile +
78                             "' to append to.");
79     }
80     OS << ErrorOrBuf.get()->getBuffer().trim() << '\n';
81   }
82 
83   auto &NameSpecPair = *Iter;
84   llvm::Record *FunctionSpec = NameSpecPair.second;
85   llvm::Record *RetValSpec = FunctionSpec->getValueAsDef("Return");
86   llvm::Record *ReturnType = RetValSpec->getValueAsDef("ReturnType");
87   std::string ReturnTypeString = Indexer.getTypeAsString(ReturnType);
88   bool ShouldReturn = true;
89   // We are generating C wrappers in C++ code. So, we should convert the C
90   // _Noreturn to the C++ [[noreturn]].
91   llvm::StringRef NR("_Noreturn "); // Note the space after _Noreturn
92   llvm::StringRef RT(ReturnTypeString);
93   if (RT.startswith(NR)) {
94     RT = RT.drop_front(NR.size() - 1); // - 1 because of the space.
95     ReturnTypeString = std::string("[[noreturn]]") + std::string(RT);
96     ShouldReturn = false;
97   }
98   OS << "extern \"C\" " << ReturnTypeString << " " << FunctionName << "(";
99 
100   auto ArgsList = FunctionSpec->getValueAsListOfDefs("Args");
101   std::stringstream CallArgs;
102   std::string ArgPrefix("__arg");
103   for (size_t i = 0; i < ArgsList.size(); ++i) {
104     llvm::Record *ArgType = ArgsList[i]->getValueAsDef("ArgType");
105     auto TypeName = Indexer.getTypeAsString(ArgType);
106 
107     if (TypeName.compare("void") == 0) {
108       if (ArgsList.size() == 1) {
109         break;
110       } else {
111         // the reason this is a fatal error is that a void argument means this
112         // function has no arguments; multiple copies of no arguments is an
113         // error.
114         llvm::PrintFatalError(
115             "The specification for function " + FunctionName +
116             " lists other arguments along with a void argument.");
117       }
118     }
119 
120     OS << TypeName << " " << ArgPrefix << i;
121     CallArgs << ArgPrefix << i;
122     if (i < ArgsList.size() - 1) {
123       OS << ", ";
124       CallArgs << ", ";
125     }
126   }
127 
128   if (EmitAlias) {
129     OS << ") __attribute__((alias(\"" << GetAliaseeName() << "\")));\n";
130   } else {
131     // TODO: Arg types of the C++ implementation functions need not
132     // match the standard types. Either handle such differences here, or
133     // avoid such a thing in the implementations.
134     OS << ") {\n"
135        << "  " << (ShouldReturn ? "return " : "")
136        << "__llvm_libc::" << FunctionName << "(" << CallArgs.str() << ");\n"
137        << "}\n";
138   }
139   return false;
140 }
141 
142 int main(int argc, char *argv[]) {
143   llvm::cl::ParseCommandLineOptions(argc, argv);
144   return TableGenMain(argv[0], WrapperGenMain);
145 }
146