• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2010, The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "slang.h"
18 
19 #include <stdlib.h>
20 
21 #include <cstring>
22 #include <list>
23 #include <sstream>
24 #include <string>
25 #include <utility>
26 #include <vector>
27 
28 #include "clang/AST/ASTConsumer.h"
29 #include "clang/AST/ASTContext.h"
30 
31 #include "clang/Basic/DiagnosticIDs.h"
32 #include "clang/Basic/DiagnosticOptions.h"
33 #include "clang/Basic/FileManager.h"
34 #include "clang/Basic/FileSystemOptions.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Basic/TargetOptions.h"
39 
40 #include "clang/Frontend/DependencyOutputOptions.h"
41 #include "clang/Frontend/FrontendDiagnostic.h"
42 #include "clang/Frontend/FrontendOptions.h"
43 #include "clang/Frontend/PCHContainerOperations.h"
44 #include "clang/Frontend/TextDiagnosticPrinter.h"
45 #include "clang/Frontend/Utils.h"
46 
47 #include "clang/Lex/HeaderSearch.h"
48 #include "clang/Lex/HeaderSearchOptions.h"
49 #include "clang/Lex/Preprocessor.h"
50 #include "clang/Lex/PreprocessorOptions.h"
51 
52 #include "clang/Parse/ParseAST.h"
53 
54 #include "clang/Sema/SemaDiagnostic.h"
55 
56 #include "llvm/ADT/IntrusiveRefCntPtr.h"
57 
58 #include "llvm/Bitcode/ReaderWriter.h"
59 
60 // More force linking
61 #include "llvm/Linker/Linker.h"
62 
63 // Force linking all passes/vmcore stuffs to libslang.so
64 #include "llvm/LinkAllIR.h"
65 #include "llvm/LinkAllPasses.h"
66 
67 #include "llvm/Support/raw_ostream.h"
68 #include "llvm/Support/MemoryBuffer.h"
69 #include "llvm/Support/ErrorHandling.h"
70 #include "llvm/Support/ManagedStatic.h"
71 #include "llvm/Support/Path.h"
72 #include "llvm/Support/TargetSelect.h"
73 #include "llvm/Support/ToolOutputFile.h"
74 
75 #include "os_sep.h"
76 #include "rs_cc_options.h"
77 #include "slang_assert.h"
78 #include "slang_backend.h"
79 
80 #include "slang_rs_context.h"
81 #include "slang_rs_export_type.h"
82 
83 #include "slang_rs_reflection.h"
84 #include "slang_rs_reflection_cpp.h"
85 #include "slang_rs_reflection_state.h"
86 
87 namespace {
88 
89 static const char *kRSTriple32 = "renderscript32-none-linux-gnueabi";
90 static const char *kRSTriple64 = "renderscript64-none-linux-gnueabi";
91 
92 }  // namespace
93 
94 namespace slang {
95 
96 
97 #define FS_SUFFIX  "fs"
98 
99 #define RS_HEADER_SUFFIX  "rsh"
100 
101 /* RS_HEADER_ENTRY(name) */
102 #define ENUM_RS_HEADER()  \
103   RS_HEADER_ENTRY(rs_allocation_create) \
104   RS_HEADER_ENTRY(rs_allocation_data) \
105   RS_HEADER_ENTRY(rs_atomic) \
106   RS_HEADER_ENTRY(rs_convert) \
107   RS_HEADER_ENTRY(rs_core) \
108   RS_HEADER_ENTRY(rs_debug) \
109   RS_HEADER_ENTRY(rs_for_each) \
110   RS_HEADER_ENTRY(rs_graphics) \
111   RS_HEADER_ENTRY(rs_graphics_types) \
112   RS_HEADER_ENTRY(rs_io) \
113   RS_HEADER_ENTRY(rs_math) \
114   RS_HEADER_ENTRY(rs_matrix) \
115   RS_HEADER_ENTRY(rs_object_info) \
116   RS_HEADER_ENTRY(rs_object_types) \
117   RS_HEADER_ENTRY(rs_quaternion) \
118   RS_HEADER_ENTRY(rs_time) \
119   RS_HEADER_ENTRY(rs_value_types) \
120   RS_HEADER_ENTRY(rs_vector_math) \
121 
122 
123 // The named of metadata node that pragma resides (should be synced with
124 // bcc.cpp)
125 const llvm::StringRef Slang::PragmaMetadataName = "#pragma";
126 
127 static llvm::LLVMContext globalContext;
128 
getGlobalLLVMContext()129 llvm::LLVMContext &getGlobalLLVMContext() { return globalContext; }
130 
131 static inline llvm::tool_output_file *
OpenOutputFile(const char * OutputFile,llvm::sys::fs::OpenFlags Flags,std::error_code & EC,clang::DiagnosticsEngine * DiagEngine)132 OpenOutputFile(const char *OutputFile,
133                llvm::sys::fs::OpenFlags Flags,
134                std::error_code &EC,
135                clang::DiagnosticsEngine *DiagEngine) {
136   slangAssert((OutputFile != nullptr) &&
137               (DiagEngine != nullptr) && "Invalid parameter!");
138 
139   EC = llvm::sys::fs::create_directories(
140       llvm::sys::path::parent_path(OutputFile));
141   if (!EC) {
142     llvm::tool_output_file *F =
143           new llvm::tool_output_file(OutputFile, EC, Flags);
144     if (F != nullptr)
145       return F;
146   }
147 
148   // Report error here.
149   DiagEngine->Report(clang::diag::err_fe_error_opening)
150     << OutputFile << EC.message();
151 
152   return nullptr;
153 }
154 
createTarget(uint32_t BitWidth)155 void Slang::createTarget(uint32_t BitWidth) {
156   if (BitWidth == 64) {
157     mTargetOpts->Triple = kRSTriple64;
158   } else {
159     mTargetOpts->Triple = kRSTriple32;
160   }
161 
162   mTarget.reset(clang::TargetInfo::CreateTargetInfo(*mDiagEngine,
163                                                     mTargetOpts));
164 }
165 
createFileManager()166 void Slang::createFileManager() {
167   mFileSysOpt.reset(new clang::FileSystemOptions());
168   mFileMgr.reset(new clang::FileManager(*mFileSysOpt));
169 }
170 
createSourceManager()171 void Slang::createSourceManager() {
172   mSourceMgr.reset(new clang::SourceManager(*mDiagEngine, *mFileMgr));
173 }
174 
createPreprocessor()175 void Slang::createPreprocessor() {
176   // Default only search header file in current dir
177   clang::HeaderSearch *HeaderInfo = new clang::HeaderSearch(&getHeaderSearchOpts(),
178                                                             *mSourceMgr,
179                                                             *mDiagEngine,
180                                                             LangOpts,
181                                                             mTarget.get());
182 
183   mPP.reset(new clang::Preprocessor(&getPreprocessorOpts(),
184                                     *mDiagEngine,
185                                     LangOpts,
186                                     *mSourceMgr,
187                                     *HeaderInfo,
188                                     *this,
189                                     nullptr,
190                                     /* OwnsHeaderSearch = */true));
191   // Initialize the preprocessor
192   mPP->Initialize(getTargetInfo());
193   clang::FrontendOptions FEOpts;
194 
195   auto *Reader = mPCHContainerOperations->getReaderOrNull(
196       getHeaderSearchOpts().ModuleFormat);
197   clang::InitializePreprocessor(*mPP, getPreprocessorOpts(), *Reader, FEOpts);
198 
199   clang::ApplyHeaderSearchOptions(*HeaderInfo, getHeaderSearchOpts(), LangOpts,
200       mPP->getTargetInfo().getTriple());
201 
202   mPragmas.clear();
203 
204   std::vector<clang::DirectoryLookup> SearchList;
205   for (unsigned i = 0, e = mIncludePaths.size(); i != e; i++) {
206     if (const clang::DirectoryEntry *DE =
207             mFileMgr->getDirectory(mIncludePaths[i])) {
208       SearchList.push_back(clang::DirectoryLookup(DE,
209                                                   clang::SrcMgr::C_System,
210                                                   false));
211     }
212   }
213 
214   HeaderInfo->SetSearchPaths(SearchList,
215                              /* angledDirIdx = */1,
216                              /* systemDixIdx = */1,
217                              /* noCurDirSearch = */false);
218 
219   initPreprocessor();
220 }
221 
createASTContext()222 void Slang::createASTContext() {
223   mASTContext.reset(
224       new clang::ASTContext(LangOpts, *mSourceMgr, mPP->getIdentifierTable(),
225                             mPP->getSelectorTable(), mPP->getBuiltinInfo()));
226   mASTContext->InitBuiltinTypes(getTargetInfo());
227   initASTContext();
228 }
229 
230 clang::ASTConsumer *
createBackend(const RSCCOptions & Opts,const clang::CodeGenOptions & CodeGenOpts,llvm::raw_ostream * OS,OutputType OT)231 Slang::createBackend(const RSCCOptions &Opts, const clang::CodeGenOptions &CodeGenOpts,
232                      llvm::raw_ostream *OS, OutputType OT) {
233   auto *B = new Backend(mRSContext, &getDiagnostics(), Opts,
234                         getHeaderSearchOpts(), getPreprocessorOpts(),
235                         CodeGenOpts, getTargetOptions(), &mPragmas, OS, OT,
236                         getSourceManager(), mAllowRSPrefix, mIsFilterscript);
237   B->Initialize(getASTContext());
238   return B;
239 }
240 
Slang(uint32_t BitWidth,clang::DiagnosticsEngine * DiagEngine,DiagnosticBuffer * DiagClient)241 Slang::Slang(uint32_t BitWidth, clang::DiagnosticsEngine *DiagEngine,
242              DiagnosticBuffer *DiagClient)
243     : mDiagEngine(DiagEngine), mDiagClient(DiagClient),
244       mTargetOpts(new clang::TargetOptions()),
245       mHSOpts(new clang::HeaderSearchOptions()),
246       mPPOpts(new clang::PreprocessorOptions()),
247       mPCHContainerOperations(std::make_shared<clang::PCHContainerOperations>()),
248       mOT(OT_Default), mRSContext(nullptr), mAllowRSPrefix(false), mTargetAPI(0),
249       mVerbose(false), mIsFilterscript(false) {
250   // Please refer to include/clang/Basic/LangOptions.h to setup
251   // the options.
252   LangOpts.RTTI = 0;  // Turn off the RTTI information support
253   LangOpts.LineComment = 1;
254   LangOpts.C99 = 1;
255   LangOpts.RenderScript = 1;
256   LangOpts.LaxVectorConversions = 0;  // Do not bitcast vectors!
257   LangOpts.CharIsSigned = 1;  // Signed char is our default.
258 
259   CodeGenOpts.OptimizationLevel = 3;
260 
261   // We must set StackRealignment, because the default is for the actual
262   // Clang driver to pass this option (-mstackrealign) directly to cc1.
263   // Since we don't use Clang's driver, we need to similarly supply it.
264   // If StackRealignment is zero (i.e. the option wasn't set), then the
265   // backend assumes that it can't adjust the stack in any way, which breaks
266   // alignment for vector loads/stores.
267   CodeGenOpts.StackRealignment = 1;
268 
269   createTarget(BitWidth);
270   createFileManager();
271   createSourceManager();
272 }
273 
~Slang()274 Slang::~Slang() {
275   delete mRSContext;
276   for (ReflectedDefinitionListTy::iterator I = ReflectedDefinitions.begin(),
277                                            E = ReflectedDefinitions.end();
278        I != E; I++) {
279     delete I->getValue().first;
280   }
281 }
282 
loadModule(clang::SourceLocation ImportLoc,clang::ModuleIdPath Path,clang::Module::NameVisibilityKind Visibility,bool IsInclusionDirective)283 clang::ModuleLoadResult Slang::loadModule(
284     clang::SourceLocation ImportLoc,
285     clang::ModuleIdPath Path,
286     clang::Module::NameVisibilityKind Visibility,
287     bool IsInclusionDirective) {
288   slangAssert(0 && "Not implemented");
289   return clang::ModuleLoadResult();
290 }
291 
setInputSource(llvm::StringRef InputFile)292 bool Slang::setInputSource(llvm::StringRef InputFile) {
293   mInputFileName = InputFile.str();
294 
295   mSourceMgr->clearIDTables();
296 
297   const clang::FileEntry *File = mFileMgr->getFile(InputFile);
298   if (File) {
299     mSourceMgr->setMainFileID(mSourceMgr->createFileID(File,
300         clang::SourceLocation(), clang::SrcMgr::C_User));
301   }
302 
303   if (mSourceMgr->getMainFileID().isInvalid()) {
304     mDiagEngine->Report(clang::diag::err_fe_error_reading) << InputFile;
305     return false;
306   }
307 
308   return true;
309 }
310 
setOutput(const char * OutputFile)311 bool Slang::setOutput(const char *OutputFile) {
312   std::error_code EC;
313   llvm::tool_output_file *OS = nullptr;
314 
315   switch (mOT) {
316     case OT_Dependency:
317     case OT_Assembly:
318     case OT_LLVMAssembly: {
319       OS = OpenOutputFile(OutputFile, llvm::sys::fs::F_Text, EC, mDiagEngine);
320       break;
321     }
322     case OT_Nothing: {
323       break;
324     }
325     case OT_Object:
326     case OT_Bitcode: {
327       OS = OpenOutputFile(OutputFile, llvm::sys::fs::F_None, EC, mDiagEngine);
328       break;
329     }
330     default: {
331       llvm_unreachable("Unknown compiler output type");
332     }
333   }
334 
335   if (EC)
336     return false;
337 
338   mOS.reset(OS);
339 
340   mOutputFileName = OutputFile;
341 
342   return true;
343 }
344 
setDepOutput(const char * OutputFile)345 bool Slang::setDepOutput(const char *OutputFile) {
346   std::error_code EC;
347 
348   mDOS.reset(
349       OpenOutputFile(OutputFile, llvm::sys::fs::F_Text, EC, mDiagEngine));
350   if (EC || (mDOS.get() == nullptr))
351     return false;
352 
353   mDepOutputFileName = OutputFile;
354 
355   return true;
356 }
357 
generateDepFile(bool PhonyTarget)358 int Slang::generateDepFile(bool PhonyTarget) {
359   if (mDiagEngine->hasErrorOccurred())
360     return 1;
361   if (mDOS.get() == nullptr)
362     return 1;
363 
364   // Initialize options for generating dependency file
365   clang::DependencyOutputOptions DepOpts;
366   DepOpts.IncludeSystemHeaders = 1;
367   if (PhonyTarget)
368     DepOpts.UsePhonyTargets = 1;
369   DepOpts.OutputFile = mDepOutputFileName;
370   DepOpts.Targets = mAdditionalDepTargets;
371   DepOpts.Targets.push_back(mDepTargetBCFileName);
372   for (std::vector<std::string>::const_iterator
373            I = mGeneratedFileNames.begin(), E = mGeneratedFileNames.end();
374        I != E;
375        I++) {
376     DepOpts.Targets.push_back(*I);
377   }
378   mGeneratedFileNames.clear();
379 
380   // Per-compilation needed initialization
381   createPreprocessor();
382   clang::DependencyFileGenerator::CreateAndAttachToPreprocessor(*mPP.get(), DepOpts);
383 
384   // Inform the diagnostic client we are processing a source file
385   mDiagClient->BeginSourceFile(LangOpts, mPP.get());
386 
387   // Go through the source file (no operations necessary)
388   clang::Token Tok;
389   mPP->EnterMainSourceFile();
390   do {
391     mPP->Lex(Tok);
392   } while (Tok.isNot(clang::tok::eof));
393 
394   mPP->EndSourceFile();
395 
396   // Declare success if no error
397   if (!mDiagEngine->hasErrorOccurred())
398     mDOS->keep();
399 
400   // Clean up after compilation
401   mPP.reset();
402   mDOS.reset();
403 
404   return mDiagEngine->hasErrorOccurred() ? 1 : 0;
405 }
406 
compile(const RSCCOptions & Opts)407 int Slang::compile(const RSCCOptions &Opts) {
408   if (mDiagEngine->hasErrorOccurred())
409     return 1;
410   if (mOS.get() == nullptr)
411     return 1;
412 
413   // Here is per-compilation needed initialization
414   createPreprocessor();
415   createASTContext();
416 
417   mBackend.reset(createBackend(Opts, CodeGenOpts, &mOS->os(), mOT));
418 
419   // Inform the diagnostic client we are processing a source file
420   mDiagClient->BeginSourceFile(LangOpts, mPP.get());
421 
422   // The core of the slang compiler
423   ParseAST(*mPP, mBackend.get(), *mASTContext);
424 
425   // Inform the diagnostic client we are done with previous source file
426   mDiagClient->EndSourceFile();
427 
428   // Declare success if no error
429   if (!mDiagEngine->hasErrorOccurred())
430     mOS->keep();
431 
432   // The compilation ended, clear
433   mBackend.reset();
434   mOS.reset();
435 
436   return mDiagEngine->hasErrorOccurred() ? 1 : 0;
437 }
438 
setDebugMetadataEmission(bool EmitDebug)439 void Slang::setDebugMetadataEmission(bool EmitDebug) {
440   if (EmitDebug)
441     CodeGenOpts.setDebugInfo(clang::codegenoptions::FullDebugInfo);
442   else
443     CodeGenOpts.setDebugInfo(clang::codegenoptions::NoDebugInfo);
444 }
445 
setOptimizationLevel(llvm::CodeGenOpt::Level OptimizationLevel)446 void Slang::setOptimizationLevel(llvm::CodeGenOpt::Level OptimizationLevel) {
447   CodeGenOpts.OptimizationLevel = OptimizationLevel;
448 }
449 
isFilterscript(const char * Filename)450 bool Slang::isFilterscript(const char *Filename) {
451   const char *c = strrchr(Filename, '.');
452   if (c && !strncmp(FS_SUFFIX, c + 1, strlen(FS_SUFFIX) + 1)) {
453     return true;
454   } else {
455     return false;
456   }
457 }
458 
generateJavaBitcodeAccessor(const std::string & OutputPathBase,const std::string & PackageName,const std::string * LicenseNote)459 bool Slang::generateJavaBitcodeAccessor(const std::string &OutputPathBase,
460                                           const std::string &PackageName,
461                                           const std::string *LicenseNote) {
462   RSSlangReflectUtils::BitCodeAccessorContext BCAccessorContext;
463 
464   BCAccessorContext.rsFileName = getInputFileName().c_str();
465   BCAccessorContext.bc32FileName = mOutput32FileName.c_str();
466   BCAccessorContext.bc64FileName = mOutputFileName.c_str();
467   BCAccessorContext.reflectPath = OutputPathBase.c_str();
468   BCAccessorContext.packageName = PackageName.c_str();
469   BCAccessorContext.licenseNote = LicenseNote;
470   BCAccessorContext.bcStorage = BCST_JAVA_CODE;   // Must be BCST_JAVA_CODE
471   BCAccessorContext.verbose = false;
472 
473   return RSSlangReflectUtils::GenerateJavaBitCodeAccessor(BCAccessorContext);
474 }
475 
checkODR(const char * CurInputFile)476 bool Slang::checkODR(const char *CurInputFile) {
477   for (RSContext::ExportableList::iterator I = mRSContext->exportable_begin(),
478           E = mRSContext->exportable_end();
479        I != E;
480        I++) {
481     RSExportable *RSE = *I;
482     if (RSE->getKind() != RSExportable::EX_TYPE)
483       continue;
484 
485     RSExportType *ET = static_cast<RSExportType *>(RSE);
486     if (ET->getClass() != RSExportType::ExportClassRecord)
487       continue;
488 
489     RSExportRecordType *ERT = static_cast<RSExportRecordType *>(ET);
490 
491     // Artificial record types (create by us not by user in the source) always
492     // conforms the ODR.
493     if (ERT->isArtificial())
494       continue;
495 
496     // Key to lookup ERT in ReflectedDefinitions
497     llvm::StringRef RDKey(ERT->getName());
498     ReflectedDefinitionListTy::const_iterator RD =
499         ReflectedDefinitions.find(RDKey);
500 
501     if (RD != ReflectedDefinitions.end()) {
502       const RSExportRecordType *Reflected = RD->getValue().first;
503 
504       // See RSExportRecordType::matchODR for the logic
505       if (!Reflected->matchODR(ERT, true)) {
506         unsigned DiagID = mDiagEngine->getCustomDiagID(
507             clang::DiagnosticsEngine::Error,
508             "type '%0' in different translation unit (%1 v.s. %2) "
509             "has incompatible type definition");
510         getDiagnostics().Report(DiagID) << Reflected->getName()
511                                         << getInputFileName()
512                                         << RD->getValue().second;
513         return false;
514       }
515     } else {
516       llvm::StringMapEntry<ReflectedDefinitionTy> *ME =
517           llvm::StringMapEntry<ReflectedDefinitionTy>::Create(RDKey);
518       ME->setValue(std::make_pair(ERT, CurInputFile));
519 
520       if (!ReflectedDefinitions.insert(ME)) {
521         slangAssert(false && "Type shouldn't be in map yet!");
522       }
523 
524       // Take the ownership of ERT such that it won't be freed in ~RSContext().
525       ERT->keep();
526     }
527   }
528   return true;
529 }
530 
initPreprocessor()531 void Slang::initPreprocessor() {
532   clang::Preprocessor &PP = getPreprocessor();
533 
534   std::stringstream RSH;
535   RSH << PP.getPredefines();
536   RSH << "#define RS_VERSION " << mTargetAPI << "\n";
537   RSH << "#include \"rs_core." RS_HEADER_SUFFIX "\"\n";
538   PP.setPredefines(RSH.str());
539 }
540 
initASTContext()541 void Slang::initASTContext() {
542   mRSContext = new RSContext(getPreprocessor(),
543                              getASTContext(),
544                              getTargetInfo(),
545                              &mPragmas,
546                              mTargetAPI,
547                              mVerbose);
548 }
549 
IsRSHeaderFile(const char * File)550 bool Slang::IsRSHeaderFile(const char *File) {
551 #define RS_HEADER_ENTRY(name)  \
552   if (::strcmp(File, #name "." RS_HEADER_SUFFIX) == 0)  \
553     return true;
554 ENUM_RS_HEADER()
555 #undef RS_HEADER_ENTRY
556   return false;
557 }
558 
IsLocInRSHeaderFile(const clang::SourceLocation & Loc,const clang::SourceManager & SourceMgr)559 bool Slang::IsLocInRSHeaderFile(const clang::SourceLocation &Loc,
560                                   const clang::SourceManager &SourceMgr) {
561   clang::FullSourceLoc FSL(Loc, SourceMgr);
562   clang::PresumedLoc PLoc = SourceMgr.getPresumedLoc(FSL);
563 
564   const char *Filename = PLoc.getFilename();
565   if (!Filename) {
566     return false;
567   } else {
568     return IsRSHeaderFile(llvm::sys::path::filename(Filename).data());
569   }
570 }
571 
compile(const std::list<std::pair<const char *,const char * >> & IOFiles64,const std::list<std::pair<const char *,const char * >> & IOFiles32,const std::list<std::pair<const char *,const char * >> & DepFiles,const RSCCOptions & Opts,clang::DiagnosticOptions & DiagOpts,ReflectionState * RState)572 bool Slang::compile(
573     const std::list<std::pair<const char*, const char*> > &IOFiles64,
574     const std::list<std::pair<const char*, const char*> > &IOFiles32,
575     const std::list<std::pair<const char*, const char*> > &DepFiles,
576     const RSCCOptions &Opts,
577     clang::DiagnosticOptions &DiagOpts,
578     ReflectionState *RState) {
579   if (IOFiles32.empty())
580     return true;
581 
582   if (Opts.mEmitDependency && (DepFiles.size() != IOFiles32.size())) {
583     unsigned DiagID = mDiagEngine->getCustomDiagID(
584         clang::DiagnosticsEngine::Error,
585         "invalid parameter for output dependencies files.");
586     getDiagnostics().Report(DiagID);
587     return false;
588   }
589 
590   if (Opts.mEmit3264 && (IOFiles64.size() != IOFiles32.size())) {
591     slangAssert(false && "Should have equal number of 32/64-bit files");
592     return false;
593   }
594 
595   std::string RealPackageName;
596 
597   const char *InputFile, *Output64File, *Output32File, *BCOutputFile,
598              *DepOutputFile;
599 
600   setIncludePaths(Opts.mIncludePaths);
601   setOutputType(Opts.mOutputType);
602   if (Opts.mEmitDependency) {
603     setAdditionalDepTargets(Opts.mAdditionalDepTargets);
604   }
605 
606   setDebugMetadataEmission(Opts.mDebugEmission);
607 
608   setOptimizationLevel(Opts.mOptimizationLevel);
609 
610   mAllowRSPrefix = Opts.mAllowRSPrefix;
611 
612   mTargetAPI = Opts.mTargetAPI;
613   if (mTargetAPI != SLANG_DEVELOPMENT_TARGET_API &&
614       (mTargetAPI < SLANG_MINIMUM_TARGET_API ||
615        mTargetAPI > SLANG_MAXIMUM_TARGET_API)) {
616     unsigned DiagID = mDiagEngine->getCustomDiagID(
617         clang::DiagnosticsEngine::Error,
618         "target API level '%0' is out of range ('%1' - '%2')");
619     getDiagnostics().Report(DiagID) << mTargetAPI << SLANG_MINIMUM_TARGET_API
620                                     << SLANG_MAXIMUM_TARGET_API;
621     return false;
622   }
623 
624   if (mTargetAPI >= SLANG_M_TARGET_API) {
625     LangOpts.NativeHalfArgsAndReturns = 1;
626     LangOpts.NativeHalfType = 1;
627     LangOpts.HalfArgsAndReturns = 1;
628   }
629 
630   mVerbose = Opts.mVerbose;
631 
632   // Skip generation of warnings a second time if we are doing more than just
633   // a single pass over the input file.
634   bool SuppressAllWarnings = (Opts.mOutputType != Slang::OT_Dependency);
635 
636   bool doReflection = true;
637   if (Opts.mEmit3264 && (Opts.mBitWidth == 32)) {
638     // Skip reflection on the 32-bit path if we are going to emit it on the
639     // 64-bit path.
640     doReflection = false;
641   }
642 
643   std::list<std::pair<const char*, const char*> >::const_iterator
644       IOFile64Iter = IOFiles64.begin(),
645       IOFile32Iter = IOFiles32.begin(),
646       DepFileIter = DepFiles.begin();
647 
648   ReflectionState::Tentative TentativeRState(RState);
649   if (Opts.mEmit3264) {
650     if (Opts.mBitWidth == 32)
651       RState->openJava32(IOFiles32.size());
652     else {
653       slangAssert(Opts.mBitWidth == 64);
654       RState->openJava64();
655     }
656   }
657 
658   for (unsigned i = 0, e = IOFiles32.size(); i != e; i++) {
659     InputFile = IOFile64Iter->first;
660     Output64File = IOFile64Iter->second;
661     Output32File = IOFile32Iter->second;
662 
663     if (!setInputSource(InputFile))
664       return false;
665 
666     if (!setOutput(Output64File))
667       return false;
668 
669     // For use with 64-bit compilation/reflection. This only sets the filename of
670     // the 32-bit bitcode file, and doesn't actually verify it already exists.
671     mOutput32FileName = Output32File;
672 
673     mIsFilterscript = isFilterscript(InputFile);
674 
675     CodeGenOpts.MainFileName = mInputFileName;
676 
677     if (Slang::compile(Opts) > 0)
678       return false;
679 
680     if (!Opts.mJavaReflectionPackageName.empty()) {
681       mRSContext->setReflectJavaPackageName(Opts.mJavaReflectionPackageName);
682     }
683     const std::string &RealPackageName =
684         mRSContext->getReflectJavaPackageName();
685 
686     if (Opts.mOutputType != Slang::OT_Dependency) {
687 
688       if (Opts.mBitcodeStorage == BCST_CPP_CODE) {
689         if (doReflection) {
690           const std::string &outputFileName = (Opts.mBitWidth == 64) ?
691               mOutputFileName : mOutput32FileName;
692           RSReflectionCpp R(mRSContext, Opts.mJavaReflectionPathBase,
693                             getInputFileName(), outputFileName);
694           if (!R.reflect()) {
695             return false;
696           }
697         }
698       } else {
699         if (!Opts.mRSPackageName.empty()) {
700           mRSContext->setRSPackageName(Opts.mRSPackageName);
701         }
702 
703         std::vector<std::string> generatedFileNames;
704         RSReflectionJava R(mRSContext, &generatedFileNames,
705                            Opts.mJavaReflectionPathBase, getInputFileName(),
706                            mOutputFileName,
707                            Opts.mBitcodeStorage == BCST_JAVA_CODE,
708                            RState);
709         if (!R.reflect()) {
710           // TODO Is this needed or will the error message have been printed
711           // already? and why not for the C++ case?
712           fprintf(stderr, "RSContext::reflectToJava : failed to do reflection "
713                           "(%s)\n",
714                   R.getLastError());
715           return false;
716         }
717 
718         if (doReflection) {
719           for (std::vector<std::string>::const_iterator
720                    I = generatedFileNames.begin(), E = generatedFileNames.end();
721                I != E;
722                I++) {
723             std::string ReflectedName = RSSlangReflectUtils::ComputePackagedPath(
724                 Opts.mJavaReflectionPathBase.c_str(),
725                 (RealPackageName + OS_PATH_SEPARATOR_STR + *I).c_str());
726             appendGeneratedFileName(ReflectedName + ".java");
727           }
728 
729           if ((Opts.mOutputType == Slang::OT_Bitcode) &&
730               (Opts.mBitcodeStorage == BCST_JAVA_CODE) &&
731               !generateJavaBitcodeAccessor(Opts.mJavaReflectionPathBase,
732                                            RealPackageName.c_str(),
733                                            mRSContext->getLicenseNote())) {
734             return false;
735           }
736         }
737       }
738     }
739 
740     if (Opts.mEmitDependency) {
741       BCOutputFile = DepFileIter->first;
742       DepOutputFile = DepFileIter->second;
743 
744       setDepTargetBC(BCOutputFile);
745 
746       if (!setDepOutput(DepOutputFile))
747         return false;
748 
749       if (SuppressAllWarnings) {
750         getDiagnostics().setSuppressAllDiagnostics(true);
751       }
752       if (generateDepFile(Opts.mEmitPhonyDependency) > 0)
753         return false;
754       if (SuppressAllWarnings) {
755         getDiagnostics().setSuppressAllDiagnostics(false);
756       }
757 
758       DepFileIter++;
759     }
760 
761     if (!checkODR(InputFile))
762       return false;
763 
764     IOFile64Iter++;
765     IOFile32Iter++;
766   }
767 
768   if (Opts.mEmit3264) {
769     if (Opts.mBitWidth == 32)
770       RState->closeJava32();
771     else {
772       slangAssert(Opts.mBitWidth == 64);
773       RState->closeJava64();
774     }
775   }
776   TentativeRState.ok();
777 
778   return true;
779 }
780 
781 }  // namespace slang
782