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