Range-based-for implementation compiles in g++ but not in clang++ - c++

The following range-based-for snippet compiles fine in g++ 4.6.1, but not with clang++ version 3.1 (trunk 151577) on oneiric amd64.
A very basic range-based for (eg std::vector) seems to work fine, so something is wrong with my implementation for my own enumerations.
I am looking for a sanity-check or a work-around.
If someone has a work-around for range-based-for that clang++ is happy with, that would be fantastic.
template< typename E >
class Enum
{
public:
Enum() : m_e( E::Last ) { }
Enum( E t ) : m_e( t ) { }
E operator()() const
{
return m_e;
}
public:
class Iterator
{
public:
Iterator( int val ) : m_val( val ) { }
E operator*( void ) const
{
return (E) m_val;
}
void operator++( void )
{
++m_val;
}
bool operator!=( Iterator rhs ) const
{
return m_val != rhs.m_val;
}
private:
int m_val;
};
private:
E m_e;
};
enum class eCOLORS
{
kBLUE=0, kGREEN, kRED, kPURPLE,
First=kBLUE, Last=kPURPLE
};
Enum<eCOLORS>::Iterator begin(const Enum<eCOLORS>& b)
{
return Enum<eCOLORS>::Iterator( (int)(eCOLORS::First ));
}
Enum<eCOLORS>::Iterator end(const Enum<eCOLORS>& b)
{
return Enum<eCOLORS>::Iterator( (int)(eCOLORS::Last ));
}
int main()
{
Enum<eCOLORS> e;
// for( const auto x : Enum<eCOLORS>() )
for( auto it=begin(e);
it!=end(e); ++it )
{
}
}
The errors are listed below
clang++ -g -std=c++0x \
sandbox.cpp -o sandbox
clang: /mnt/home/foobar/src/llvm/tools/clang/lib/AST/Decl.cpp:1001: bool clang::NamedDecl::isCXXInstanceMember() const: Assertion `isCXXClassMember() && "checking whether non-member is instance member"' failed.
0 clang 0x0000000001aecc4f
1 clang 0x0000000001aed179
2 libpthread.so.0 0x00002aeeaeda1060
3 libc.so.6 0x00002aeeaf98b3a5 gsignal + 53
4 libc.so.6 0x00002aeeaf98eb0b abort + 379
5 libc.so.6 0x00002aeeaf983d4d __assert_fail + 221
6 clang 0x0000000000ed8f9e clang::NamedDecl::isCXXInstanceMember() const + 174
7 clang 0x0000000000a51095 clang::Sema::CheckQualifiedMemberReference(clang::Expr*, clang::QualType, clang::CXXScopeSpec const&, clang::LookupResult const&) + 213
8 clang 0x0000000000a55520 clang::Sema::BuildMemberReferenceExpr(clang::Expr*, clang::QualType, clang::SourceLocation, bool, clang::CXXScopeSpec const&, clang::SourceLocation, clang::NamedDecl*, clang::LookupResult&, clang::TemplateArgumentListInfo const*, bool) + 672
9 clang 0x0000000000a518d4 clang::Sema::BuildMemberReferenceExpr(clang::Expr*, clang::QualType, clang::SourceLocation, bool, clang::CXXScopeSpec&, clang::SourceLocation, clang::NamedDecl*, clang::DeclarationNameInfo const&, clang::TemplateArgumentListInfo const*) + 772
10 clang 0x0000000000b50378
11 clang 0x0000000000b58a19
12 clang 0x0000000000b56362
13 clang 0x0000000000b4e87b clang::Sema::SubstExpr(clang::Expr*, clang::MultiLevelTemplateArgumentList const&) + 75
14 clang 0x0000000000b64a69 clang::Sema::SubstInitializer(clang::Expr*, clang::MultiLevelTemplateArgumentList const&, bool) + 169
15 clang 0x0000000000b6d57f clang::Sema::InstantiateMemInitializers(clang::CXXConstructorDecl*, clang::CXXConstructorDecl const*, clang::MultiLevelTemplateArgumentList const&) + 1135
16 clang 0x0000000000b6cb13 clang::Sema::InstantiateFunctionDefinition(clang::SourceLocation, clang::FunctionDecl*, bool, bool) + 2307
17 clang 0x0000000000b6dadd clang::Sema::PerformPendingInstantiations(bool) + 461
18 clang 0x00000000008e0bb3 clang::Sema::ActOnEndOfTranslationUnit() + 419
19 clang 0x00000000008757d0 clang::Parser::ParseTopLevelDecl(clang::OpaquePtr<clang::DeclGroupRef>&) + 112
20 clang 0x00000000008727c6 clang::ParseAST(clang::Sema&, bool) + 326
21 clang 0x000000000075623e clang::CodeGenAction::ExecuteAction() + 958
22 clang 0x0000000000612f3d clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) + 957
23 clang 0x00000000005fb55a clang::ExecuteCompilerInvocation(clang::CompilerInstance*) + 3098
24 clang 0x00000000005f17ce cc1_main(char const**, char const**, char const*, void*) + 5918
25 clang 0x00000000005f7679 main + 729
26 libc.so.6 0x00002aeeaf97630d __libc_start_main + 237
27 clang 0x00000000005effe9
Stack dump:
0. Program arguments: /usr/local/bin/clang -cc1 -triple x86_64-unknown-linux-gnu -emit-obj -mrelax-all -disable-free -main-file-name sandbox.cpp -mrelocation-model static -mdisable-fp-elim -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -momit-leaf-frame-pointer -g -resource-dir /usr/local/bin/../lib/clang/3.1 -I /home/kfeng/dev/pitbull/cpp/inc/ -I /home/kfeng/src/stlsoft/include/ -I /home/kfeng/src/gtest/include/ -I /home/kfeng/src/gmock/include/ -I /home/kfeng/src/pantheios/include/ -fmodule-cache-path /var/tmp/clang-module-cache -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../include/c++/4.6 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../include/c++/4.6/x86_64-linux-gnu -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../include/c++/4.6/backward -internal-isystem /usr/local/include -internal-isystem /usr/local/bin/../lib/clang/3.1/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -std=c++0x -fdeprecated-macro -fdebug-compilation-dir /home/kfeng/dev/pitbull/cpp/sbx -ferror-limit 19 -fmessage-length 181 -mstackrealign -fgnu-runtime -fobjc-runtime-has-arc -fobjc-runtime-has-weak -fobjc-fragile-abi -fcxx-exceptions -fexceptions -fdiagnostics-show-option -fcolor-diagnostics -o /tmp/sandbox-0nnyL0.o -x c++ sandbox.cpp
1. <eof> parser at end of file
2. sandbox.cpp:5:2: instantiating function definition 'Enum'
clang: error: unable to execute command: Aborted
clang: error: clang frontend command failed due to signal (use -v to see invocation)
clang: note: diagnostic msg: Please submit a bug report to http://llvm.org/bugs/ and include command line arguments and all diagnostic information.
clang: note: diagnostic msg: Preprocessed source(s) and associated run script(s) are located at:
clang: note: diagnostic msg: /tmp/sandbox-Fp11tf.ii
clang: note: diagnostic msg: /tmp/sandbox-Fp11tf.sh

This compiles for me with the stable release of clang. Looks like it's a bug in trunk.
% clang --version
clang version 3.0 (tags/RELEASE_30/final)
Target: x86_64-unknown-linux-gnu
Thread model: posix
% clang++ -o test test.cc -std=c++0x
%

Related

Is this an Apple compiler v14 optimization bug?

Source code:
#include <cstdio>
static const char encodeBase64Table[64 + 1] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int main() {
// create decoding table
unsigned long invalid = 64;
unsigned long decodeBase64Table[256] = {};
for (unsigned long i = 0; i < 256; i++)
decodeBase64Table[i] = invalid;
for (unsigned long i = 0; i < 64; i++) {
decodeBase64Table[(unsigned char)encodeBase64Table[i]] = i;
}
printf("decodeBase64Table[65] = %lu\n", decodeBase64Table[65]);
return 0;
}
Apple Clang 11.0.3 (expected output, even with -O3):
/t/s/1673994196 ❯❯❯ /usr/bin/clang++ --version
Apple clang version 11.0.3 (clang-1103.0.32.62)
Target: x86_64-apple-darwin21.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
/t/s/1673994196 ❯❯❯ /usr/bin/clang++ -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk -O3 -std=c++17 a.cpp
/t/s/1673994196 ❯❯❯ ./a.out
decodeBase64Table[65] = 0
Apple Clang 14.0.0 (unexpected output, only with -O3):
/t/s/1673994196 ❯❯❯ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ --version
Apple clang version 14.0.0 (clang-1400.0.29.202)
Target: x86_64-apple-darwin21.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
/t/s/1673994196 ❯❯❯ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk -O3 -std=c++17 a.cpp
/t/s/1673994196 ❯❯❯ ./a.out
decodeBase64Table[65] = 64

How to insert machine instruction using BuildMI() correctly inside a MachineFunctionPass in LLVM?

I wrote my MachineFunctionPass following this blog: https://www.kharghoshal.xyz/blog/writing-machinefunctionpass
Then ported it for RISCV target. It was working well.
I also add iteration for each instruction to check for Call instruction. It still working, until I tried to write instruction.
This is my MachineFunctionPass:
#include "RISCV.h"
#include "RISCVInstrInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
using namespace llvm;
#define RISCV_MACHINEINSTR_PRINTER_PASS_NAME \
"Dummy RISCV machineinstr printer pass"
namespace {
class RISCVMachineInstrPrinter : public MachineFunctionPass {
public:
static char ID;
RISCVMachineInstrPrinter() : MachineFunctionPass(ID) {
initializeRISCVMachineInstrPrinterPass(*PassRegistry::getPassRegistry());
}
bool runOnMachineFunction(MachineFunction &MF) override;
StringRef getPassName() const override {
return RISCV_MACHINEINSTR_PRINTER_PASS_NAME;
}
};
char RISCVMachineInstrPrinter::ID = 0;
bool RISCVMachineInstrPrinter::runOnMachineFunction(MachineFunction &MF) {
for (auto &MBB : MF) {
for (auto &MI : MBB) {
if (MI.isCall()) {
outs() << "Found Call\n";
outs() << MI.getOpcode() << "\n";
RISCVInstrInfo *XII; // target instruction info
DebugLoc DL;
MachineBasicBlock::iterator MBBI = BuildMI(MBB, MI ,DL, XII->get(RISCV::SW), RISCV::X1)
.addReg(RISCV::X31)
.addImm(0);
return true;
}
}
}
return false;
}
} // end of anonymous namespace
INITIALIZE_PASS(RISCVMachineInstrPrinter, "RISCV-machineinstr-printer",
RISCV_MACHINEINSTR_PRINTER_PASS_NAME,
true, // is CFG only?
true // is analysis?
)
namespace llvm {
FunctionPass *createRISCVMachineInstrPrinterPass() {
return new RISCVMachineInstrPrinter();
}
} // namespace llvm
When I tried to compile my code using
clang hi.c -o hi -march=rv32g --target=riscv32
The output was an error message that I do not understand:
Found Call
202
PLEASE submit a bug report to https://bugs.llvm.org/ and include the crash backtrace, preprocessed source, and associated run script.
Stack dump:
0. Program arguments: /home/ibndias/riscv32/bin/clang-12 -cc1 -triple riscv32-- -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name hi.c -mrelocation-model static -mframe-pointer=all -fmath-errno -fno-rounding-math -mconstructor-aliases -nostdsysteminc -target-feature +m -target-feature +a -target-feature +f -target-feature +d -target-feature +relax -target-feature -save-restore -target-abi ilp32d -msmall-data-limit 8 -fno-split-dwarf-inlining -debugger-tuning=gdb -resource-dir /home/ibndias/riscv32/lib/clang/12.0.0 -isysroot /home/ibndias/riscv32/riscv32-unknown-elf -internal-isystem /home/ibndias/riscv32/riscv32-unknown-elf/include -fdebug-compilation-dir /home/ibndias/Documents/Projects -ferror-limit 19 -fno-signed-char -fgnuc-version=4.2.1 -fcolor-diagnostics -faddrsig -o /tmp/hi-047c57.o -x c hi.c
1. <eof> parser at end of file
2. Code generation
3. Running pass 'Function Pass Manager' on module 'hi.c'.
4. Running pass 'Dummy RISCV machineinstr printer pass' on function '#main'
#0 0x000055c4c194489e llvm::sys::PrintStackTrace(llvm::raw_ostream&) (/home/ibndias/riscv32/bin/clang-12+0x185589e)
#1 0x000055c4c1942734 llvm::sys::RunSignalHandlers() (/home/ibndias/riscv32/bin/clang-12+0x1853734)
#2 0x000055c4c1942878 SignalHandler(int) (/home/ibndias/riscv32/bin/clang-12+0x1853878)
#3 0x00007f3f492a23c0 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x153c0)
#4 0x000055c4c0b72ae2 (anonymous namespace)::RISCVMachineInstrPrinter::runOnMachineFunction(llvm::MachineFunction&) (/home/ibndias/riscv32/bin/clang-12+0xa83ae2)
#5 0x000055c4c0e8901c llvm::MachineFunctionPass::runOnFunction(llvm::Function&) (/home/ibndias/riscv32/bin/clang-12+0xd9a01c)
#6 0x000055c4c12ca770 llvm::FPPassManager::runOnFunction(llvm::Function&) (/home/ibndias/riscv32/bin/clang-12+0x11db770)
#7 0x000055c4c12cbd79 llvm::FPPassManager::runOnModule(llvm::Module&) (/home/ibndias/riscv32/bin/clang-12+0x11dcd79)
#8 0x000055c4c12c9980 llvm::legacy::PassManagerImpl::run(llvm::Module&) (/home/ibndias/riscv32/bin/clang-12+0x11da980)
#9 0x000055c4c1be7b26 (anonymous namespace)::EmitAssemblyHelper::EmitAssembly(clang::BackendAction, std::unique_ptr<llvm::raw_pwrite_stream, std::default_delete<llvm::raw_pwrite_stream> >) (/home/ibndias/riscv32/bin/clang-12+0x1af8b26)
#10 0x000055c4c1be94ce clang::EmitBackendOutput(clang::DiagnosticsEngine&, clang::HeaderSearchOptions const&, clang::CodeGenOptions const&, clang::TargetOptions const&, clang::LangOptions const&, llvm::DataLayout const&, llvm::Module*, clang::BackendAction, std::unique_ptr<llvm::raw_pwrite_stream, std::default_delete<llvm::raw_pwrite_stream> >) (/home/ibndias/riscv32/bin/clang-12+0x1afa4ce)
#11 0x000055c4c2863fd1 clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&) (/home/ibndias/riscv32/bin/clang-12+0x2774fd1)
#12 0x000055c4c360db39 clang::ParseAST(clang::Sema&, bool, bool) (/home/ibndias/riscv32/bin/clang-12+0x351eb39)
#13 0x000055c4c21fb239 clang::FrontendAction::Execute() (/home/ibndias/riscv32/bin/clang-12+0x210c239)
#14 0x000055c4c21af54b clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) (/home/ibndias/riscv32/bin/clang-12+0x20c054b)
#15 0x000055c4c22cd800 clang::ExecuteCompilerInvocation(clang::CompilerInstance*) (/home/ibndias/riscv32/bin/clang-12+0x21de800)
#16 0x000055c4c0b1ca57 cc1_main(llvm::ArrayRef<char const*>, char const*, void*) (/home/ibndias/riscv32/bin/clang-12+0xa2da57)
#17 0x000055c4c0b1a60b ExecuteCC1Tool(llvm::SmallVectorImpl<char const*>&) (/home/ibndias/riscv32/bin/clang-12+0xa2b60b)
#18 0x000055c4c0ab1cde main (/home/ibndias/riscv32/bin/clang-12+0x9c2cde)
#19 0x00007f3f48d530b3 __libc_start_main /build/glibc-YYA7BZ/glibc-2.31/csu/../csu/libc-start.c:342:3
#20 0x000055c4c0b1a19e _start (/home/ibndias/riscv32/bin/clang-12+0xa2b19e)
clang-12: error: unable to execute command: Segmentation fault (core dumped)
clang-12: error: clang frontend command failed due to signal (use -v to see invocation)
clang version 12.0.0 (https://github.com/llvm/llvm-project.git 99ad956fdaee5398fdcf46fa49cb433cf52dc461)
Target: riscv32--
Thread model: posix
InstalledDir: /home/ibndias/riscv32/bin
clang-12: note: diagnostic msg:
********************
PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
Preprocessed source(s) and associated run script(s) are located at:
clang-12: note: diagnostic msg: /tmp/hi-5c6fca.c
clang-12: note: diagnostic msg: /tmp/hi-5c6fca.sh
clang-12: note: diagnostic msg:
********************
And this is my code:
#include<stdio.h>
int foo(int a, int b)
{
return a + b;
}
int main()
{
int a, b, c;
a = 0x10;
b = 0x20;
c = foo(a,b);
return c;
}
Is this a correct way to insert instruction?
for (auto &MBB : MF) {
for (auto &MI : MBB) {
if (MI.isCall()) {
outs() << "Found Call\n";
outs() << MI.getOpcode() << "\n";
RISCVInstrInfo *XII; // target instruction info
DebugLoc DL;
MachineBasicBlock::iterator MBBI = BuildMI(MBB, MI ,DL, XII->get(RISCV::SW), RISCV::X1)
.addReg(RISCV::X31)
.addImm(0);
return true;
}
}
}
You are using MBBI to give the position to the buildMI while it is not yet initialized.
what I understand is that you want to add an instruction before the call so you should use MI instead of MBBI as the second parameter.
The target instruction info (XII) is not initialized also.
You can take a look here:
https://llvm.org/docs/CodeGenerator.html#id23

LLVM Segmentation fault on basic function pass

I'm completely new to LLVM. I tried to follow the functions in the following article. This is the function pass that is defined there:
#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
namespace {
struct SkeletonPass : public FunctionPass {
static char ID;
SkeletonPass() : FunctionPass(ID) {}
virtual bool runOnFunction(Function &F) {
for (auto &B : F) {
for (auto &I : B) {
if (auto *op = dyn_cast<BinaryOperator>(&I)) {
// Insert at the point where the instruction `op` appears.
IRBuilder<> builder(op);
// Make a multiply with the same operands as `op`.
Value *lhs = op->getOperand(0);
Value *rhs = op->getOperand(1);
Value *mul = builder.CreateMul(lhs, rhs);
// Everywhere the old instruction was used as an operand, use our
// new multiply instruction instead.
for (auto &U : op->uses()) {
User *user = U.getUser(); // A User is anything with operands.
user->setOperand(U.getOperandNo(), mul);
}
// We modified the code.
return true;
}
}
}
return false;
}
};
}
char SkeletonPass::ID = 0;
// Automatically enable the pass.
// http://adriansampson.net/blog/clangpass.html
static void registerSkeletonPass(const PassManagerBuilder &,
legacy::PassManagerBase &PM) {
PM.add(new SkeletonPass());
}
static RegisterStandardPasses
RegisterMyPass(PassManagerBuilder::EP_EarlyAsPossible,
registerSkeletonPass);
Then compiled the file:
$ cd llvm-pass-skeleton
$ mkdir build
$ cd build
$ cmake .. # Generate the Makefile.
$ make # Actually build the pass.
And run it using:
/usr/local/opt/llvm/bin/clang -Xclang -load -Xclang build/skeleton/libSkeletonPass.so example.c
Where example.c is:
#include <stdio.h>
int main(int argc, const char** argv) {
int num;
scanf("%i", &num);
printf("%i\n", num + 2);
return 0;
}
I'm on Mac OS X Mojave and I installed LLVM using homebrew and put it in my PATH.
I get the following error message
clang version 9.0.0 (tags/RELEASE_900/final)
Target: x86_64-apple-darwin18.7.0
Thread model: posix
InstalledDir: /usr/local/Cellar/llvm/9.0.0_1/bin
"/usr/local/Cellar/llvm/9.0.0_1/bin/clang-9" -cc1 -triple x86_64-apple-macosx10.14.0 -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name example.c -mrelocation-model pic -pic-level 2 -mthread-model posix -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu penryn -dwarf-column-info -debugger-tuning=lldb -ggnu-pubnames -target-linker-version 512.4 -v -resource-dir /usr/local/Cellar/llvm/9.0.0_1/lib/clang/9.0.0 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/local/include -internal-isystem /usr/local/Cellar/llvm/9.0.0_1/lib/clang/9.0.0/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -fdebug-compilation-dir /Users/BN/Documents/Library/CS/Compilers/LLVM/llvm-pass-skeleton -ferror-limit 19 -fmessage-length 80 -stack-protector 1 -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fobjc-runtime=macosx-10.14.0 -fmax-type-align=16 -fdiagnostics-show-option -fcolor-diagnostics -load build/skeleton/libSkeletonPass.so -o /var/folders/cf/1_hzh5h91x90j4xx_h1mlb4w0000gp/T/example-4b27ba.o -x c example.c
clang -cc1 version 9.0.0 based upon LLVM 9.0.0 default target x86_64-apple-darwin18.7.0
ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/local/include"
ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/Library/Frameworks"
#include "..." search starts here:
#include <...> search starts here:
/usr/local/Cellar/llvm/9.0.0_1/lib/clang/9.0.0/include
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks (framework directory)
End of search list.
Stack dump:
0. Program arguments: /usr/local/Cellar/llvm/9.0.0_1/bin/clang-9 -cc1 -triple x86_64-apple-macosx10.14.0 -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name example.c -mrelocation-model pic -pic-level 2 -mthread-model posix -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu penryn -dwarf-column-info -debugger-tuning=lldb -ggnu-pubnames -target-linker-version 512.4 -v -resource-dir /usr/local/Cellar/llvm/9.0.0_1/lib/clang/9.0.0 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/local/include -internal-isystem /usr/local/Cellar/llvm/9.0.0_1/lib/clang/9.0.0/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -fdebug-compilation-dir /Users/BN/Documents/Library/CS/Compilers/LLVM/llvm-pass-skeleton -ferror-limit 19 -fmessage-length 80 -stack-protector 1 -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fobjc-runtime=macosx-10.14.0 -fmax-type-align=16 -fdiagnostics-show-option -fcolor-diagnostics -load build/skeleton/libSkeletonPass.so -o /var/folders/cf/1_hzh5h91x90j4xx_h1mlb4w0000gp/T/example-4b27ba.o -x c example.c
0 clang-9 0x00000001071fba46 llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 40
1 clang-9 0x00000001071fbe98 SignalHandler(int) + 180
2 libsystem_platform.dylib 0x00007fff6f2aeb5d _sigtramp + 29
3 libsystem_platform.dylib 0x0000000000000001 _sigtramp + 18446603338651079873
4 clang-9 0x0000000106e94485 llvm::object_deleter<llvm::SmallVector<std::__1::pair<llvm::PassManagerBuilder::ExtensionPointTy, std::__1::function<void (llvm::PassManagerBuilder const&, llvm::legacy::PassManagerBase&)> >, 8u> >::call(void*) + 19
5 clang-9 0x00000001071abc95 llvm::llvm_shutdown() + 53
6 clang-9 0x0000000107193061 llvm::InitLLVM::~InitLLVM() + 15
7 clang-9 0x0000000106034857 main + 7249
8 libdyld.dylib 0x00007fff6f0c33d5 start + 1
clang-9: error: unable to execute command: Segmentation fault: 11
clang-9: error: clang frontend command failed due to signal (use -v to see invocation)
clang version 9.0.0 (tags/RELEASE_900/final)
Target: x86_64-apple-darwin18.7.0
Thread model: posix
InstalledDir: /usr/local/Cellar/llvm/9.0.0_1/bin
clang-9: note: diagnostic msg: PLEASE submit a bug report to https://bugs.llvm.org/ and include the crash backtrace, preprocessed source, and associated run script.
clang-9: error: unable to execute command: Segmentation fault: 11
clang-9: note: diagnostic msg: Error generating preprocessed source(s).
The error message states that the two non-existant directories /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/local/include and /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/Library/Frameworks will be ignored. These directories are actually installed under /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include and /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library, respectively. Not sure whether this is relevant and how to tell Clang to look in those locations.
Can somebody help me with this please?

How to clone function from another module and set it AlwaysInline on LLVM pass?

I want to clone a function from another bitcode module and set it AlwaysInline so that it can be inlined.
But an error occurs when applying such custom pass (It seems that the cause is the use of CloneFunction()). How can I fix it?
I'm using LLVM 3.6.0 on OS X and target is Android armeabi-v7a (It should be same on other target).
callee.cpp (compiled to bitcode module callee.bc)
#include <jni.h>
#include <android/log.h>
#ifdef __cplusplus
extern "C" {
#endif
void callee(char *str, int num)
{
__android_log_print(ANDROID_LOG_DEBUG, "target", "%s, 0x%x", str, num);
}
#ifdef __cplusplus
}
#endif
test.cpp (a module custom pass is applied)
#include <jni.h>
#ifdef __cplusplus
extern "C" {
#endif
void caller()
{
}
void Java_com_android_test_TestActivity_test(JNIEnv *env, jobject thiz)
{
caller();
}
#ifdef __cplusplus
}
#endif
TestPass.cpp (a custom pass)
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
using namespace llvm;
namespace {
struct TestPass : public ModulePass {
static char ID;
TestPass() : ModulePass(ID) {}
virtual bool runOnModule(Module &M)
{
for (Module::iterator F = M.begin(), E = M.end(); F!= E; ++F)
{
if (F->getName() == "caller")
{
inst_iterator I = inst_begin(F);
Instruction *inst = &*I;
SMDiagnostic error;
LLVMContext context;
std::unique_ptr<Module> m = parseIRFile("callee.bc", error, context);
for (Module::iterator f = m->getFunctionList().begin(); f != m->getFunctionList().end(); f++)
{
if (f->getName() == "callee")
{
// Copy callee.bc callee function to current module and set AlwaysInline
ValueToValueMapTy VMap;
Function* callee_clone = CloneFunction(f, VMap, false);
/*
callee_clone->setName("callee_clone");
callee_clone->addFnAttr(Attribute::AlwaysInline);
M.getFunctionList().push_back(callee_clone);
// Add call to copied callee function
GlobalVariable* str = new GlobalVariable(M,
ArrayType::get(IntegerType::get(M.getContext(), 8), 8),
false,
GlobalValue::ExternalLinkage,
0,
"str");
str->setAlignment(1);
Constant* str_init = ConstantDataArray::getString(M.getContext(), "abcdefgh", false);
str->setInitializer(str_init);
ConstantInt* param1_indice1 = ConstantInt::get(M.getContext(), APInt(32, StringRef("0"), 10));
ConstantInt* param1_indice2 = ConstantInt::get(M.getContext(), APInt(32, StringRef("0"), 10));
std::vector<Constant*> param1_indices;
param1_indices.push_back(param1_indice1);
param1_indices.push_back(param1_indice2);
Constant* param1 = ConstantExpr::getGetElementPtr(str, param1_indices);
GlobalVariable* num = new GlobalVariable(M,
IntegerType::get(M.getContext(), 32),
false,
GlobalValue::ExternalLinkage,
0,
"num");
num->setAlignment(4);
ConstantInt* num_init = ConstantInt::get(M.getContext(), APInt(32, StringRef("12345"), 10));
num->setInitializer(num_init);
LoadInst* param2 = new LoadInst(num, "", false, inst);
param2->setAlignment(4);
std::vector<Value*> params;
params.push_back(param1);
params.push_back(param2);
CallInst* ci = CallInst::Create(callee_clone, params, "", inst);
ci->setCallingConv(CallingConv::C);
ci->setTailCall(false);
*/
}
}
}
}
return true;
}
};
}
char TestPass::ID = 0;
static RegisterPass<TestPass> X("TestPass", "TestPass", false, false);
static void registerTestPass(const PassManagerBuilder &, legacy::PassManagerBase &PM)
{
PM.add(new TestPass());
}
static RegisterStandardPasses RegisterTestPass(PassManagerBuilder::EP_ModuleOptimizerEarly, registerTestPass);
Error applying custom pass
[...snip...]
While deleting: [7 x i8]* %.str
Use still stuck around after Def is destroyed:#.str = private unnamed_addr constant [7 x i8] <null operand!>, align 1
Assertion failed: (use_empty() && "Uses remain when a value is destroyed!"), function ~Value, file /private/tmp/llvm/llvm-3.6.0.src/lib/IR/Value.cpp, line 81.
0 clang++ 0x000000011154d909 llvm::sys::PrintStackTrace(__sFILE*) + 57
1 clang++ 0x000000011154e07b SignalHandler(int) + 555
2 libsystem_platform.dylib 0x00007fffb7debb3a _sigtramp + 26
3 libsystem_platform.dylib 0x00000000509ff1d0 _sigtramp + 2562799280
4 clang++ 0x000000011154de36 abort + 22
5 clang++ 0x000000011154de11 __assert_rtn + 81
6 clang++ 0x00000001114f2104 llvm::Value::~Value() + 660
7 clang++ 0x00000001114a63d1 llvm::GlobalVariable::~GlobalVariable() + 97
8 clang++ 0x00000001114e3ba9 llvm::Module::~Module() + 105
9 TestPass.dylib 0x000000011254d7dc (anonymous namespace)::TestPass::runOnModule(llvm::Module&) + 524
10 clang++ 0x00000001114cdc4e llvm::legacy::PassManagerImpl::run(llvm::Module&) + 1054
11 clang++ 0x000000010f43f49a clang::EmitBackendOutput(clang::DiagnosticsEngine&, clang::CodeGenOptions const&, clang::TargetOptions const&, clang::LangOptions const&, llvm::StringRef, llvm::Module*, clang::BackendAction, llvm::raw_ostream*) + 7098
12 clang++ 0x000000010f57433d clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&) + 509
13 clang++ 0x000000010f609954 clang::ParseAST(clang::Sema&, bool, bool) + 468
14 clang++ 0x000000010f27aa53 clang::FrontendAction::Execute() + 67
15 clang++ 0x000000010f24cb2c clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) + 956
16 clang++ 0x000000010f20763a clang::ExecuteCompilerInvocation(clang::CompilerInstance*) + 4154
17 clang++ 0x000000010f1fe65c cc1_main(llvm::ArrayRef<char const*>, char const*, void*) + 1068
18 clang++ 0x000000010f2057ec main + 11660
19 libdyld.dylib 0x00007fffb7bdc235 start + 1
20 libdyld.dylib 0x0000000000000066 start + 1212300850
Stack dump:
0. Program arguments: /opt/llvm-3.6.0/build/Release+Asserts/bin/clang++ -cc1 -triple thumbv7-none-linux-androideabi -S -disable-free -main-file-name test.cpp -mrelocation-model pic -pic-level 1 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -no-integrated-as -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu cortex-a8 -target-feature +soft-float-abi -target-feature +vfp3 -target-feature +d16 -target-feature -neon -target-abi aapcs-linux -mfloat-abi soft -target-linker-version 253.3 -g -dwarf-column-info -ffunction-sections -coverage-file /opt/test/obj/local/armeabi-v7a/objs/test/test.o -resource-dir /opt/llvm-3.6.0/build/Release+Asserts/bin/../lib/clang/3.6.0 -dependency-file /opt/test/obj/local/armeabi-v7a/objs/test/test.o.d -MT /opt/test/obj/local/armeabi-v7a/objs/test/test.o -MP -D NDEBUG -D ANDROID -I /Applications/android-ndk-r10e/sources/cxx-stl/llvm-libc++/libcxx/include -I /Applications/android-ndk-r10e/sources/cxx-stl/llvm-libc++/../llvm-libc++abi/libcxxabi/include -I /Applications/android-ndk-r10e/sources/cxx-stl/llvm-libc++/../../android/support/include -I /opt/test/jni -I /Applications/android-ndk-r10e/platforms/android-21/arch-arm/usr/include -internal-isystem /usr/local/include -internal-isystem /opt/llvm-3.6.0/build/Release+Asserts/bin/../lib/clang/3.6.0/include -internal-externc-isystem /include -internal-externc-isystem /usr/include -O1 -Wno-invalid-command-line-argument -Wno-unused-command-line-argument -Wformat -Werror=format-security -std=c++11 -fdeprecated-macro -fno-dwarf-directory-asm -fdebug-compilation-dir /opt/test/jni -ferror-limit 19 -fmessage-length 152 -stack-protector 2 -mstackrealign -fno-rtti -fno-signed-char -fobjc-runtime=gcc -fdiagnostics-show-option -fcolor-diagnostics -load /opt/test/TestPass.dylib -mllvm -debug-pass=Structure -o /var/folders/vq/53lxh89j7ts1rtc9gfg_s7f80000gq/T/test-f2326e.s -x c++ /opt/test/jni/test.cpp
1. <eof> parser at end of file
2. Per-module optimization passes
3. Running pass 'TestPass' on module '/opt/test/jni/test.cpp'.
clang++: error: unable to execute command: Illegal instruction: 4
clang++: error: clang frontend command failed due to signal (use -v to see invocation)
clang version 3.6.0 (tags/RELEASE_360/final)
Target: armv7-none-linux-androideabi
Thread model: posix
clang++: note: diagnostic msg: PLEASE submit a bug report to http://llvm.org/bugs/ and include the crash backtrace, preprocessed source, and associated run script.
clang++: note: diagnostic msg:
********************
PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
Preprocessed source(s) and associated run script(s) are located at:
clang++: note: diagnostic msg: /var/folders/vq/53lxh89j7ts1rtc9gfg_s7f80000gq/T/test-773901.cpp
clang++: note: diagnostic msg: /var/folders/vq/53lxh89j7ts1rtc9gfg_s7f80000gq/T/test-773901.sh
clang++: note: diagnostic msg:
********************
make: *** [/opt/test/obj/local/armeabi-v7a/objs/test/test.o] Error 254

What are the compiler options used by Xcode for universal build?

As seen in the image below.
Click here for image
I have selected the Universal architecture for compiling c++ code. I would now like to do the same from terminal.
I tried to use the options
-arch x86_64, -arch i386, -m32, -m64
but i keep getting the following error.
$ g++ -dynamiclib myclass.cc -I hashlib2plus/header/ -L hashlib2plus/lib/ -o myclass.so -v
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin15.3.0
Thread model: posix
"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -cc1 -triple x86_64-apple-macosx10.11.0 -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -main-file-name myclass.cc -mrelocation-model pic -pic-level 2 -mthread-model posix -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu core2 -target-linker-version 253.9 -v -dwarf-column-info -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/7.0.2 -I hashlib2plus/header/ -stdlib=libc++ -fdeprecated-macro -fdebug-compilation-dir /Users/akshaythakare/temp/cpp_dll -ferror-limit 19 -fmessage-length 80 -stack-protector 1 -mstackrealign -fblocks -fobjc-runtime=macosx-10.11.0 -fencode-extended-block-signature -fcxx-exceptions -fexceptions -fmax-type-align=16 -fdiagnostics-show-option -fcolor-diagnostics -o /var/folders/xs/1kz_zcnj1v324_rkdx_ftbx00000gn/T/myclass-13c695.o -x c++ myclass.cc
clang -cc1 version 7.0.2 based upon LLVM 3.7.0svn default target x86_64-apple-darwin15.3.0
ignoring nonexistent directory "/usr/include/c++/v1"
#include "..." search starts here:
#include <...> search starts here:
hashlib2plus/header
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1
/usr/local/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/7.0.2/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
End of search list.
"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -dynamic -dylib -arch x86_64 -macosx_version_min 10.11.0 -o myclass.so -Lhashlib2plus/lib/ /var/folders/xs/1kz_zcnj1v324_rkdx_ftbx00000gn/T/myclass-13c695.o -lc++ -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/7.0.2/lib/darwin/libclang_rt.osx.a
Undefined symbols for architecture x86_64:
"sha512wrapper::sha512wrapper()", referenced from:
MyClass::hashCheck() in myclass-13c695.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
And yes the code was running normally when being run from Xcode.
Here's my code in case anyone knows how to resolve the error
MyClass.h
#ifndef _MYCLASS_H_
#define _MYCLASS_H_
class MyClass{
public:
MyClass();
/* Use virtual otherwise linker will try to perform static linkage */
virtual int hashCheck();
};
#endif
MyClass.cc
#include "myclass.h"
#include <dlfcn.h>
#include <iostream>
#include <dirent.h>
#include <vector>
#include "hashlib2plus/header/hashlibpp.h"
// g++ -dynamiclib -flat_namespace myclass.cc -o myclass.so
// hashlib2plus/hl_sha2ext.cpp hashlib2plus/hl_sha512wrapper.cpp
using namespace std;
void hasher(std::string);
std::vector <std::string> vecFile;
extern "C" MyClass* create_object(){
return new MyClass;
}
extern "C" void destroy_object(MyClass* object){
delete object;
}
MyClass::MyClass(){}
std::string globalMasterHash = "sd239d023md302k23s02ssd239d023md302k23s02ssd239d023md302k23s02ssd239d023md302k23s02s";
int MyClass::hashCheck(){
std::string masterHash = "";
hashwrapper *myWrapper = new sha512wrapper();
std::string parentDir = "./static/";
hasher(parentDir);
while(vecFile.empty() != true){
std::string hash2 = myWrapper->getHashFromFile(vecFile.back());
vecFile.pop_back();
masterHash = myWrapper->getHashFromString(hash2 + masterHash);
}
std::cout << masterHash << std::endl;
if(masterHash.compare(globalMasterHash) == 0){
return 1;
} else {
return 0;
}
return 0;
}
void hasher(std::string curr_directory){
DIR *dir;
dirent *ent;
if((dir = opendir(curr_directory.c_str())) != NULL){
while ((ent = readdir(dir))!=NULL){
if(ent->d_name[0] != '.'){
std::string path = curr_directory + ent->d_name;
if (ent->d_type == DT_DIR){
path += "/";
hasher(path);
} else {
vecFile.push_back(path);
}
}
}
}
return;
}
The lib i am linking click here